Retrofit 文件file 和实例对象一起上传

情景:要求传递一个文件和一个对象实例

定义

   @Multipart
    @POST(FileUrl.PREFIX + FileUrl.PATH_VEHICLE_LARGE_FILE_UPLOAD)
    Observable<FileUploadResDto> vehicleLargeFileUpload(@PartMap Map<String, RequestBody> map,@Part MultipartBody.Part file);

调用

 @Override
    public void vehicleLargeFileUpload(String path, FileUploadReqDto fileUploadReqDto,
                                       ResultCallback<FileUploadResDto> callback) {
        Map<String, RequestBody> map = new HashMap<>();
        //@PartMap    传实例对象
        Map<String, Object> requestMap = fileUploadReqDto.toMap();
        for (String key : requestMap.keySet()) {//text/plain
            map.put(key,
                    RequestBody.create(MediaType.parse("text/plain"), requestMap.get(key) + ""));
            FLog.i("key=" + key + " value=" + requestMap.get(key) + "");
        }
        // @Part     传文件   
        File file = new File(path);//application/octet-stream  mutipart/form-data
        RequestBody fileBody = RequestBody.create(MediaType.parse("mutipart/form-data"), file);
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), fileBody);
        getApi().vehicleLargeFileUpload(map,filePart).subscribe(new FObserver<>(callback));
    }

实例对象的tomap()方法


    public Map<String, Object> toMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("businessData", businessData);
        map.put("chunkNumber", chunkNumber);
        map.put("fileName", fileName);
        map.put("identifier", identifier);
        map.put("totalChunks", totalChunks);
        map.put("vin", vin);
//        map.put("uploadId", uploadId);
        map.put("key", key);
        map.put("folderType", folderType);
        return map;
    }

传递结果
在这里插入图片描述
在这里插入图片描述
也可以就只用@PartMap

@Multipart
    @POST(FileUrl.PREFIX + FileUrl.PATH_VEHICLE_LARGE_FILE_UPLOAD)
    Observable<FileUploadResDto> vehicleLargeFileUpload(@PartMap Map<String, RequestBody> map);

调用

 public void vehicleLargeFileUpload(String path, FileUploadReqDto fileUploadReqDto,
                                       ResultCallback<FileUploadResDto> callback) {
        Map<String, RequestBody> map = new HashMap<>();

        File file = new File(path);
        RequestBody fileBody = RequestBody.create(MediaType.parse("mutipart/form-data"), file);
        map.put("file\"; filename=\"" + file.getName(), fileBody);

        Map<String, Object> requestMap = fileUploadReqDto.toMap();
        for (String key : requestMap.keySet()) {
            map.put(key,
                    RequestBody.create(MediaType.parse("text/plain"), requestMap.get(key) + ""));
            FLog.i("key=" + key + " value=" + requestMap.get(key) + "");
        }

        getApi().vehicleLargeFileUpload(map).subscribe(new FObserver<>(callback));
    }

注:上传文字内容需要指定 text/plain ;
上传图片 : 要加上 filename

map.put("file\"; filename=\"" + file.getName(), fileBody);  
是固定格式,传文件就这么传
再比如传图片格式
map.put("photo\";filename=\"" + file.getName(), fileBody)

只是上传单张图片的话也可以
@Multipart 
@PUT("/myuser/info/update/") 
Observable<UserUploadBean> updateUserInfo(@Part("photo\";filename=\"file.jpg\"") RequestBody photo);

有多张图片的话和其他参数,建议使用 PartMap 进行操作
@Multipart 
@PUT("/myuser/info/update/") 
Observable<UserUploadBean> updateUserInfo(@PartMap Map<String, RequestBody> params);
Map<String, RequestBody> bodys = new HashMap<>(); 
bodys.put("first_name", requestDesc); 
bodys.put("photo\";filename=\"" + file.getName(), requestFile);
bodys.put("photo1\";filename=\"" + file.getName(), requestFile1);


如果上传图片和其他参数也可以
@Multipart
@PUT("/myuser/info/update/") 
Observable<UserUploadBean> updateUserInfo(@Part("photo") RequestBody photo, @Part("name") RequestBody name);
RequestBody requestFile = RequestBody.create(MediaType.parse("image/png"), file);  
RequestBody requestDesc = RequestBody.create(MediaType.parse("text/plain"), userName);


原文链接:https://www.jianshu.com/p/a3e162261ab6

Retrofit 的注解类型

在这里插入图片描述
第一类:网络请求方法
在这里插入图片描述
详细说明:
a. @GET、@POST、@PUT、@DELETE、@HEAD
以上方法分别对应 HTTP中的网络请求方式

public interface GetRequest_Interface {

    @GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
    Call<Translation>  getCall();
    // @GET注解的作用:采用Get方法发送网络请求
    // getCall() = 接收网络请求数据的方法
    // 其中返回类型为Call<*>,*是接收数据的类(即上面定义的Translation类)
}

此处特意说明URL的组成:Retrofit把 网络请求的URL 分成了两部分设置:

// 第1部分:在网络请求接口的注解设置
@GET("openapi.do?keyfrom=Yanzhikai&key=2032414398&type=data&doctype=json&version=1.1&q=car")
Call<Translation>  getCall();

// 第2部分:在创建Retrofit实例时通过.baseUrl()设置
Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/") //设置网络请求的Url地址
                .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器
                .build();

// 从上面看出:一个请求的URL可以通过 替换块 和 请求方法的参数 来进行动态的URL更新。
// 替换块是由 被{}包裹起来的字符串构成
// 即:Retrofit支持动态改变网络请求根目录

网络请求的完整 Url =在创建Retrofit实例时通过.baseUrl()设置 +网络请求接口的注解设置(下面称 “path“ )
具体整合的规则如下:
在这里插入图片描述
建议采用第三种方式来配置,并尽量使用同一种路径形式。

b. @HTTP

作用:替换@GET、@POST、@PUT、@DELETE、@HEAD注解的作用 及 更多功能拓展
具体使用:通过属性method、path、hasBody进行设置

public interface GetRequest_Interface {
    /**
     * method:网络请求的方法(区分大小写)
     * path:网络请求地址路径
     * hasBody:是否有请求体
     */
    @HTTP(method = "GET", path = "blog/{id}", hasBody = false)
    Call<ResponseBody> getCall(@Path("id") int id);
    // {id} 表示是一个变量
    // method 的值 retrofit 不会做处理,所以要自行保证准确
}

第二类:标记
在这里插入图片描述
a. @FormUrlEncoded

  • 作用:表示发送form-encoded的数据
每个键值对需要用@Filed来注解键名,随后的对象需要提供值。

b. @Multipart

  • 作用:表示发送form-encoded的数据(适用于 有文件 上传的场景)
每个键值对需要用@Part来注解键名,随后的对象需要提供值。

具体使用如下:
GetRequest_Interface

public interface GetRequest_Interface {
        /**
         *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
         * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值
         */
        @POST("/form")
        @FormUrlEncoded
        Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);
         
        /**
         * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
         * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
         */
        @POST("/form")
        @Multipart
        Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);

}

// 具体使用
       GetRequest_Interface service = retrofit.create(GetRequest_Interface.class);
        // @FormUrlEncoded 
        Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);
        
        //  @Multipart
        RequestBody name = RequestBody.create(textType, "Carson");
        RequestBody age = RequestBody.create(textType, "24");

        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
        Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePar

第三类:网络请求参数
在这里插入图片描述
详细说明

a. @Header & @Headers

  • 作用:添加请求头 &添加不固定的请求头

具体使用如下:

// @Header
@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)

// @Headers
@Headers("Authorization: authorization")
@GET("user")
Call<User> getUser()
或者
Observable<ResponseBody> userInfo(@Header("Authorization") String token, @Query("id") String id);

// 以上的效果是一致的。
// 区别在于使用场景和使用方式
// 1. 使用场景:@Header用于添加不固定的请求头,@Headers用于添加固定的请求头
// 2. 使用方式:@Header作用于方法的参数;@Headers作用于方法

b. @Body

  • 作用:以 Post方式 传递 自定义数据类型 给服务器
  • 特别注意:如果提交的是一个Map,那么作用相当于 @Field
不过Map要经过 FormBody.Builder 类处理成为符合 Okhttp 格式的表单,如:
FormBody.Builder builder = new FormBody.Builder();
builder.add("key","value");

c. @Field & @FieldMap

  • 作用:发送 Post请求 时提交请求的表单字段
  • 具体使用:与 @FormUrlEncoded 注解配合使用
public interface GetRequest_Interface {
        /**
         *表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
         * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值
         */
        @POST("/form")
        @FormUrlEncoded
        Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);

/**
         * Map的key作为表单的键
         */
        @POST("/form")
        @FormUrlEncoded
        Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);

}

// 具体使用
         // @Field
        Call<ResponseBody> call1 = service.testFormUrlEncoded1("Carson", 24);

        // @FieldMap
        // 实现的效果与上面相同,但要传入Map
        Map<String, Object> map = new HashMap<>();
        map.put("username", "Carson");
        map.put("age", 24);
        Call<ResponseBody> call2 = service.testFormUrlEncoded2(map);

d. @Part & @PartMap

  • 作用:发送 Post请求 时提交请求的表单字段
@Field的区别:功能相同,但携带的参数类型更加丰富,包括数据流,所以适用于 有文件上传 的场景

  • 具体使用:与 @Multipart 注解配合使用
public interface GetRequest_Interface {

          /**
         * {@link Part} 后面支持三种类型,{@link RequestBody}、{@link okhttp3.MultipartBody.Part} 、任意类型
         * 除 {@link okhttp3.MultipartBody.Part} 以外,其它类型都必须带上表单字段({@link okhttp3.MultipartBody.Part} 中已经包含了表单字段的信息),
         */
        @POST("/form")
        @Multipart
        Call<ResponseBody> testFileUpload1(@Part("name") RequestBody name, @Part("age") RequestBody age, @Part MultipartBody.Part file);

        /**
         * PartMap 注解支持一个Map作为参数,支持 {@link RequestBody } 类型,
         * 如果有其它的类型,会被{@link retrofit2.Converter}转换,如后面会介绍的 使用{@link com.google.gson.Gson} 的 {@link retrofit2.converter.gson.GsonRequestBodyConverter}
         * 所以{@link MultipartBody.Part} 就不适用了,所以文件只能用<b> @Part MultipartBody.Part </b>
         */
        @POST("/form")
        @Multipart
        Call<ResponseBody> testFileUpload2(@PartMap Map<String, RequestBody> args, @Part MultipartBody.Part file);

        @POST("/form")
        @Multipart
        Call<ResponseBody> testFileUpload3(@PartMap Map<String, RequestBody> args);
}

// 具体使用
 MediaType textType = MediaType.parse("text/plain");
        RequestBody name = RequestBody.create(textType, "Carson");
        RequestBody age = RequestBody.create(textType, "24");
        RequestBody file = RequestBody.create(MediaType.parse("application/octet-stream"), "这里是模拟文件的内容");

        // @Part
        MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", "test.txt", file);
        Call<ResponseBody> call3 = service.testFileUpload1(name, age, filePart);
        ResponseBodyPrinter.printResponseBody(call3);

        // @PartMap
        // 实现和上面同样的效果
        Map<String, RequestBody> fileUpload2Args = new HashMap<>();
        fileUpload2Args.put("name", name);
        fileUpload2Args.put("age", age);
        //这里并不会被当成文件,因为没有文件名(包含在Content-Disposition请求头中),但上面的 filePart 有
        //fileUpload2Args.put("file", file);
        Call<ResponseBody> call4 = service.testFileUpload2(fileUpload2Args, filePart); //单独处理文件
        ResponseBodyPrinter.printResponseBody(call4);
}

e. @Query和@QueryMap

  • 作用:用于 @GET 方法的查询参数(Query = Url 中 ‘?’ 后面的 key-value)
如:url = http://www.println.net/?cate=android,其中,Query = cate

  • 具体使用:配置时只需要在接口方法中增加一个参数即可:
  @GET("/")    
   Call<String> cate(@Query("cate") String cate);
}

// 其使用方式同 @Field与@FieldMap,这里不作过多描述

 @Field@FieldMap 体现在请求体上,@Query@QueryMap 体现在url上

f. @Path

  • 作用:URL地址的缺省值
  • 具体使用:
public interface GetRequest_Interface {

        @GET("users/{user}/repos")
        Call<ResponseBody>  getBlog(@Path("user") String user );
        // 访问的API是:https://api.github.com/users/{user}/repos
        // 在发起请求时, {user} 会被替换为方法的第一个参数 user(被@Path注解作用)
    }

g. @Url

  • 作用:直接传入一个请求的 URL变量 用于URL设置
  • 具体使用:
public interface GetRequest_Interface {

        @GET
        Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);
       // 当有URL注解时,@GET传入的URL就可以省略
       // 当GET、POST...HTTP等方法中没有设置Url时,则必须使用 {@link Url}提供

}

汇总
在这里插入图片描述

参考链接:https://www.jianshu.com/p/a3e162261ab6

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值