【发布时间】: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是否为空? -
不,文件不为空