不想发送文件,但改型不允许null

时间:2018-07-30 18:16:38

标签: android file-upload retrofit2

我正在使用retofit发送原始数据以及文件。当我发送文件时,它工作正常,但是如果我不想发送文件并传递null,则应用程序崩溃。

MyInterfcace.class

public interface MainInterface {
 @POST("contact/updateWithFile")
Call<AddCustomerModel> updateCustomerWithFile(@Body RequestBody data);
  }

Api通话

private void updateCustomerWithFiles(JSONObject obj) {
    progressBarHandler.show();


    MultipartBody.Builder builder = new MultipartBody.Builder();
    builder.setType(MultipartBody.FORM);

    builder.addFormDataPart("bodyData", String.valueOf(obj));

    if (parts.size() > 0) {
        for (int i = 0; i < parts.size(); i++) {
            File file = new File(parts.get(i));
            builder.addFormDataPart("uploadingFiles", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        }
    } else {
        File f = null;
        builder.addFormDataPart("uploadingFiles", "", RequestBody.create(MediaType.parse("multipart/form-data"), f));
    }


    File file = new File("");

    MultipartBody requestBody = builder.build();

    MainInterface apiService = ApiClient.getClient().create(MainInterface.class);

    Call<AddCustomerModel> call = apiService.updateCustomerWithFile(requestBody);

    call.enqueue(new Callback<AddCustomerModel>() {
        @Override
        public void onResponse(Call<AddCustomerModel> call, Response<AddCustomerModel> response) {
            progressBarHandler.dismiss();
            if (response.isSuccessful()) {
                finish();
                overridePendingTransition(0, 0);
            } else {
                Log.d("TAG", "No Data!!!");
            }
        }

        @Override
        public void onFailure(Call<AddCustomerModel> call, Throwable t) {
            progressBarHandler.dismiss();
        }
    });
}

我该如何解决?

1 个答案:

答案 0 :(得分:0)

改造不会将@Body设置为null,这是预期的行为

在问题讨论中,

  

当您省略body参数时,我们会发送一个没有内容类型的空body。

如果您想进一步了解为什么要做出此决定,那么请看看Square的github中讨论的问题,

https://github.com/square/retrofit/issues/1488