使用 Retrofit2 发送 json 和文件

Send json and file with Retrofit2

我曾经使用 Retrofit2 向服务器发送 POST 请求:

    @POST("goals")
    Call<Void> postGoal(@Body Goal goal);

其中目标是具有一些 String/Integer 字段的对象。

现在我需要在那里添加照片文件。 我知道我需要 switch 才能使用 Multipart:

    @Multipart
    @POST("goals")
    Call<Void> postGoal(
            @Part("picture") RequestBody picture
            );

//...
//Instantaining picture 
RequestBody.create(MediaType.parse("image/*"), path)

但是我应该如何添加以前的字段?特别是有没有一种方法可以添加整个目标对象而不用将其划分为字段?

您可以像这样添加 @Part 目标

@Multipart
    @POST("goals")
    Call<Void> postGoal(
            @Part("picture") RequestBody picture,
            @Part("goal") RequestBody goal
            );

    //...
    //Instantaining picture 
    RequestBody.create(MediaType.parse("image/*"), path)

您可以找到更多详细信息:retrofit-2-how-to-upload-files-to-server

发送 json 和文件你可以按照这样的方式进行。

@Multipart
@POST("goals")
Call<JsonModel> postGoal(@Part MultipartBody.Part file, @Part("json") RequestBody json);

现在使用 Gson 将您要作为 json 发送的对象转换为 json。 像这样。

    String json = new Gson().toJson(new Goal());

  File file = new File(path);
                        RequestBody requestFile =
                                RequestBody.create(MediaType.parse("multipart/form-data"), file);

                        // MultipartBody.Part is used to send also the actual file name
                        MultipartBody.Part body =
                                MultipartBody.Part.createFormData("picture", file.getName(), requestFile);

                        // add another part within the multipart request
                        RequestBody jsonBody=
                                RequestBody.create(
                                        MediaType.parse("multipart/form-data"), json);
                        Retrofit retrofit = new Retrofit.Builder()
                                .baseUrl(url)
                                .addConverterFactory(GsonConverterFactory.create())
                                .build();
                        RestApi api = retrofit.create(RestApi.class);
                        Call<ResponseBody> call = api.upload(jsonBody, body);
                        call.enqueue(new Callback<ResponseBody>() {
                            @Override
                            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                                Log.d("onResponse: ", "success");
                            }

                            @Override
                            public void onFailure(Call<ResponseBody> call, Throwable t) {
                                Log.d("onFailure: ", t.getLocalizedMessage());
                            }
                        });