retrofit + rxjava 图文上传到服务器


首先看后台接口要求

retrofit + rxjava 图文上传到服务器_第1张图片

需要post方法,form-data,file文件(字段名为file),其他参数
看需求,如果是文件用
MediaType.parse(“multipart/form-data”)
如果是image
MediaType.parse(“image/*”)

1.用map+body

@Multipart
@POST("app/activity")
Observable> submitAction(@PartMap() Map partMap, @Part MultipartBody.Part file);
*注意MultipartBody.Part的参数不能指定part()的Key
 File file = new File(path);
 RequestBody firstBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("file", file.getName(), firstBody);

        RequestBody titleBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), title);
        RequestBody contentBody = RequestBody.create(
                MediaType.parse("multipart/form-data"), content);
        RequestBody body3 = RequestBody.create(
        HashMap map = new HashMap<>();
        map.put("title", titleBody);
        map.put("content", contentBody);

Observable observable = api().submitAction(requestBody).map(new HttpResultFunc());
toSubscribe(observable, subscriber);
 
  

2.body

@POST("app/activity")
Observable> submitAction(@Body RequestBody Body);
File file = new File(path);
        //构建body
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("title", title)
                .addFormDataPart("content", content)
                .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
Observable observable = api().submitAction(requestBody).map(new HttpResultFunc());
toSubscribe(observable, subscriber); 
  

以上。

你可能感兴趣的:(retrofit和网络相关)