Retrofit 2.0 轻松实现文件/多图片上传/Json字符串

public interface FileUploadService {  
 @Multipart
 @POST("upload")
 Call upload(@Part("description") RequestBody description,
                          @Part MultipartBody.Part file);
}

具体用法

// 创建 RequestBody,用于封装 请求RequestBody
RequestBody requestFile =
        RequestBody.create(MediaType.parse("multipart/form-data"), file);

// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
        MultipartBody.Part.createFormData("image", file.getName(), requestFile);

// 添加描述
String descriptionString = "hello, 这是文件描述";
RequestBody description =
        RequestBody.create(
                MediaType.parse("multipart/form-data"), descriptionString);

// 执行请求
Call call = service.upload(description, body);
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call,
                           Response response) {
        Log.v("Upload", "success");
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        Log.e("Upload error:", t.getMessage());
    }
});

上报一张图片

@Multipart
 @POST("you methd url upload/")
Call uploadFile(
        @Part("avatar\\\\"; filename=\\\\"avatar.jpg") RequestBody file);
  • 1
  • 2
  • 3
  • 4
  • 5

上报多张图片

@POST("upload/")
Call uploadFiles(@Part("filename") String description,
                                     @Part("pic\\\\"; filename=\\\\"image1.png") RequestBody imgs1,
                                     @Part("pic\\\\"; filename=\\\\"image2.png") RequestBody imgs2,
                                     @Part("pic\\\\"; filename=\\\\"image3.png") RequestBody imgs3,
                                     @Part("pic\\\\"; filename=\\\\"image4.png") RequestBody imgs4);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

如果图片数量不确定

  @Multipart
@POST("{url}")
Observable uploadFiles(
        @Path("url") String url,
        @Part("filename") String description,
        @PartMap() Map maps);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

或者:

@Multipart
@POST("{url}")
Observable uploads(
        @Path("url") String url,
        @Part("description") RequestBody description,
        @Part("filekey") MultipartBody.Part file);

图片和参数同时上报

  @Multipart
@POST("upload/")
Call register(

                                   @QueryMap Map usermaps,
                                   @Part("avatar\\\\"; filename=\\\\"avatar.jpg") RequestBody avatar,
                                   );
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

此种方式让你很好的解决用户注册问题。包含用户全部信息

上面的代码片段中显示的代码初始化(RequestBody 和description),以及如何使用文件上传服务。正如已经提到的,从OkHttp RequestBody类用于描述。需要两个RequestBody.create()方法

除了描述,必须将添加文件包装成MultipartBody的实例。这就是你需要使用适当的从客户端上传文件。此外,您可以添加createFormData中的uploadFile(Uri fileUri)方法和重用

设置 Content-Type

请注意设置的内容类型。如果你拦截底层OkHttp客户机和更改内容类型application / json, 你的服务器可能反序列化过程出现的问题。请确保你没有自定义multipart/form-data

upLoad图片也可以具体指明Content-Type 为 “image/jpg”格式的

   RequestBody requestFile =
            RequestBody.create(MediaType.parse("image/jpg"), mFile);
  • 1
  • 2
  • 3

还有常用的:

上传Json

@POST("/uploadJson")
Observable uploadjson(
        @Body RequestBody jsonBody);
  • 1
  • 2
  • 3
  • 4

upLoadJson 也可以具体指明Content-Type 为 “application/json”格式的

具体组装我们的RequestBody则可以这样:

 RequestBody body= 
               RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonString);
  • 1
  • 2
  • 3

接着可以这样调用:

// 执行请求
Call call = service.uploadJson(description, body);
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call,
                           Response response) {
        Log.v("Upload", "success");
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        Log.e("Upload error:", t.getMessage());
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

}

至于服务器返回什么类型的model, 开发者可以自定义 譬如你可以把APi 中的 ResponseBody 指定为你自己的javaBean,当然上层构建Callback的时候也必须是 Call

@POST("/uploadJson")
Observable uploadjson(
        @Body RequestBody jsonBody);

你可能感兴趣的:(Retrofit 2.0 轻松实现文件/多图片上传/Json字符串)