java - RequestBody 在附加文件而不是字符串数据时始终为空
问题描述
我正在使用 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);
感谢所有的回答和评论。
解决方案
首先你需要改变你的界面。而不是@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);
}
推荐阅读
- discord - 删除消息命令,仅适用于所有者、管理员和版主
- freertos - FreeRTOS - 堆栈增加的原因?
- vb.net - 单击时搜索按钮不起作用
- c - 有没有办法在#include 中使用 char 数组/变量
- node.js - 在 CPanel(共享主机)上运行 Express Server
- python - Python - 读取多个文件并写入多个新文件
- java - JAVA - 机器人鼠标不移动实际指针
- entity-framework-core - EntityFramewor.Core 不迁移 sqite 数据库
- r - 如何转换 Excel 导入的数据以使用 Plotly 3D 曲面图?
- apache-spark - SQL get date of "when a status change"(考虑到相同的状态可以出现多次)