【问题标题】:RequestBody always null while attaching file not string dataRequestBody 在附加文件而不是字符串数据时始终为空
【发布时间】:2019-09-23 17:18:34
【问题描述】:

我正在使用 Retrofit 2.5 版,我已经查看了所有相关文档和问题,但我还没有找到任何解决方案。这里的问题是,附加文件后,文件的 RequestBody 总是变为空。这里我附上了我的代码,请看看这个-

          final RequestBody msgbody = RequestBody.create(MediaType.parse("text/plain"), messege);
                final RequestBody idbody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(id));
                //map.put("userId", idbody);
                //map.put("message", msgbody);
                RequestBody fbody = null;
                if (fileUri!=null) {
                    String path = FileUtils.getPath(getContext(),fileUri);
                    File file = new File(path);
                    fbody = RequestBody.create(MediaType.parse(getContext().getContentResolver().getType(fileUri)), file);
                    //RequestBody body = RequestBody.create(MediaType.parse("*/*"), file);
                    //fbody = MultipartBody.Part.createFormData("file", file.getName(), body);
                    Log.e("SUPPORT",path+" body:"+new Gson().toJson(fbody));
                    //map.put("file\"; filename=\""+file.getName()+"\"",body);
                }

                Call<SubmitTicket> call = mInterface.issueTicket(idbody,msgbody,fbody);
                Log.e("SUPPORT",new Gson().toJson(call));
                call.enqueue(new Callback<SubmitTicket>() {
                    @Override
                    public void onResponse(Call<SubmitTicket> call, Response<SubmitTicket> response) {
                        loadingBar.setVisibility(View.GONE);
                        submitBtn.setEnabled(true);
                   }
                   @Override
                   public void onFailure(Call<ResponseModel> call, Throwable t) {
                      t.printStackTrace();
                      Log.i("Error :",t.getCause()+"");
                      Log.i("Error :","T");
                      finish();
                   } //error even before compile**
            });

这里是接口代码,

@Multipart
@POST("Support")
//Call<SubmitTicket> issueTicket(@PartMap Map<String, RequestBody> params);
Call<SubmitTicket> issueTicket(@Part("userId") RequestBody id, @Part("message") RequestBody messege, @Part("image\"; filename=\"myfile.jpg\" ") RequestBody file);

感谢所有答案和cmets。

【问题讨论】:

  • 哪一部分是空的?
  • 看代码,附加文件后if条件变为null的变量fbody。
  • 为什么这行被评论//fbody = MultipartBody.Part.createFormData("file", file.getName(), body);
  • 您是否调试并检查您的file 是否为空?
  • 不,文件不为空

标签: java android retrofit2


【解决方案1】:

我遇到了同样的问题,所以我所做的是更改代码的这个“fbody”部分并添加一个自定义方法来返回 Multipart 主体:

      final RequestBody msgbody = RequestBody.create(MediaType.parse("text/plain"), messege);
            final RequestBody idbody = RequestBody.create(MediaType.parse("text/plain"), String.valueOf(id));
            //map.put("userId", idbody);
            //map.put("message", msgbody);
            MultipartBody.Part fbody = null;
            if (fileUri != null) {
                Log.e("SUPPORT",path+" body:"+new Gson().toJson(fbody));
                fbody = prepareFilePart("img", fileUri);
                //map.put("file\"; filename=\""+file.getName()+"\"",body);
            }

            Call<SubmitTicket> call = mInterface.issueTicket(idbody,msgbody,fbody);
            Log.e("SUPPORT",new Gson().toJson(call));
            call.enqueue(new Callback<SubmitTicket>() {
                @Override
                public void onResponse(Call<SubmitTicket> call, Response<SubmitTicket> response) {
                    loadingBar.setVisibility(View.GONE);
                    submitBtn.setEnabled(true);
               }
               @Override
               public void onFailure(Call<ResponseModel> call, Throwable t) {
                  t.printStackTrace();
                  Log.i("Error :",t.getCause()+"");
                  Log.i("Error :","T");
                  finish();
               } //error even before compile**
        });

我在这里添加了一种创建表单数据的方法:

@NonNull
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
    File file = FileUtils.getFile(this, fileUri);
    // create RequestBody instance from file
    RequestBody requestFile = RequestBody.create(file, MediaType.parse("image/jpeg"));
    // MultipartBody.Part is used to send also the actual file name
    return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}

【讨论】:

    【解决方案2】:

    首先你需要改变你的界面。不要使用@Part RequestBody file,而是使用@Part MultipartBody.Part file,如下所示-

    @Multipart
    @POST("Support")
    Call<SubmitTicket> issueTicket(@Part("userId") RequestBody id, @Part("message") RequestBody messege, @Part MultipartBody.Part  image);
    

    然后在您的请求部分使用 Mulitpart.Part 正文而不是 RequestBody 作为 跟随 -

    MultipartBody.Part fbody = null;
                    if (fileUri!=null) {
                        String path = FileUtils.getPath(getContext(),fileUri);
                        File file = new File(path);
                        //here **image** is your remote file param name
                        fbody = MultipartBody.Part.createFormData("image", file.getName()+System.currentTimeMillis(), RequestBody.create(MediaType.parse("image/*"), file));
    
                        Log.e("SUPPORT",path+" body:"+new Gson().toJson(fbody));
                        //map.put("file\"; filename=\""+file.getName()+"\"",body);
                    }
    

    【讨论】:

    • @Krishna Vyas 试试这个
    【解决方案3】:

    使用这个,这对你有帮助。您需要以 Multipart 表单数据发送文件。

    您的界面将如下所示:

     @Multipart
     @POST("Support")
     Call<SubmitTicket> issueTicket(@Part("userId") RequestBody id, @Part("message") RequestBody messege, @Part MultipartBody.Part file);
    

    你的请求会是这样的:

      RequestBody msgbody = RequestBody.create(MediaType.parse("text/plain"), "yourMessage");
            RequestBody idbody = RequestBody.create(MediaType.parse("text/plain"), "id");
    
    
            if (fileUri!=null) {
                String path = FileUtils.getPath(getContext(),fileUri);
                File file = new File(path);
    
                // create RequestBody instance from file
                RequestBody requestFile =
                        RequestBody.create(MediaType.parse("multipart/form-data"), file);
    
                MultipartBody.Part body =
                        MultipartBody.Part.createFormData("file", file.getName(), requestFile);
    
    
    
            Call<SubmitTicket> call = mInterface.issueTicket(idbody,msgbody,body);
            Log.e("SUPPORT",new Gson().toJson(call));
            call.enqueue(new Callback<SubmitTicket>() {
                @Override
                public void onResponse(Call<SubmitTicket> call, Response<SubmitTicket> response) {
                    loadingBar.setVisibility(View.GONE);
                    submitBtn.setEnabled(true);
                }
                @Override
                public void onFailure(Call<ResponseModel> call, Throwable t) {
                    t.printStackTrace();
                    Log.i("Error :",t.getCause()+"");
                    Log.i("Error :","T");
                    finish();
                } //error even before compile**
            });
    
            }
    

    这总是在帮助我。希望这些对您和其他人也有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      相关资源
      最近更新 更多