您的位置:首页 > 移动开发 > Android开发

Android开发使用retrofit上传文件和多个参数一起时失败问题

2017-07-28 12:16 1156 查看
最近使用retrofit上传文件和参数时发现上传直接失败,于是查询各种资料发现是因为retrofit上传文件时底层限制问题,可是换作另外方法上传就可以了,记录下;


一,服务器让传递的参数和内容



二,retrofit接口内容

@Multipart
@POST
Call<WebResponseBean> uploadFile(@Url String url,@Part MultipartBody.Part file, @PartMap Map<String, RequestBody> params);


三,代码中调用封装图片上传工具

public class ImageUploadUtil {
private ImageUploadUtil(){};
public static void loadFile(final Context context,String url, File file, Map map){
ApiService apiService = new RetrofitHttpUtil(context).getApiService();
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("upload", file.getName(), requestFile);
apiService.uploadFile(url,body,map)
.enqueue(new Callback<WebResponseBean>() {
@Override
public void onResponse(Call<WebResponseBean> call, Response<WebResponseBean> response) {
String msg = response.body().msg;
ToastUtil.show(context,msg);
}

@Override
public void onFailure(Call<WebResponseBean&g
4000
t; call, Throwable t) {

}
});
}
}


4,上传参数处理成retrofit底层需要的 “text/plain”

private HashMap<String, RequestBody> setParams(String tag) {
HashMap<String, RequestBody> map = new HashMap<>();
map.put("uid", toRequestBody(uid));
map.put("act", toRequestBody("UploadImage"));
map.put("tag", toRequestBody(tag));
return map;
}

private RequestBody toRequestBody(String value) {
RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), value);
return requestBody;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: