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

来源:互联网 发布:淘宝镁光内存条 编辑:程序博客网 时间:2024/05/02 01:11
  最近使用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> 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;    }
原创粉丝点击