Retrofit文件和参数上传

参数上传

1.参数个数不是很多时

@FormUrlEncoded
@POST
Call<ResponseBody> uploadParams(@Field("username")String username,@Field("token")String token);

2. 多个参数上传

@FormUrlEncoded
@POST
Call<ResponseBody> uploadParams(@FieldMap Map<String,String> map); 

3. 通用的方法

@POST
Call<ResponseBody> uploadParams(@Body RequestBody body);

调用时,传入一个RequestBody对象,OkHttp库中有一个专门用来构建参数上传的RequestBody子类,即FormBody,如下

FormBody body=new FormBody.Builder()
                .add("username","admin")
                .add("token","sjdkdjows=dmzkkshf")
                .build();

在使用的时候,直接调用uploadParams (body)即可实现上传。

文件上传

1. 单个文件上传

@Multipart
@POST
Call<ResponseBody> uploadOneFile(@Part MultipartBody.Part body);

调用的时候使用MultipartBody.Part来构造一个Part对象参数

File file = new File("E:\\1.jpg");
RequestBody requestFile = RequestBody.create(file, MediaType.parse("image/*"));
MultipartBody.Part body = MultipartBody.Part.createFormData("file_data", file.getName(), requestFile);

Call<ResponseBody> uploadCall = downloadService.uploadOneFile(body);

2. 多文件上传

@Multipart
@POST
Call<ResponseBody> uploadFiles(@Part List<MultipartBody.Part> list);

调用方法

File file1 = new File("E:\\1.jpg");
RequestBody requestFile1 = RequestBody.create(file1, MediaType.parse("image/*"));
MultipartBody.Part body1 = MultipartBody.Part.createFormData("file_data", file1.getName(), requestFile1);
File file2 = new File("E:\\2.jpg");
RequestBody requestFile2 = RequestBody.create(file2, MediaType.parse("image/*"));
MultipartBody.Part body2 = MultipartBody.Part.createFormData("file_data", file2.getName(), requestFile2);

List<MultipartBody.Part> list = new ArrayList<>();
list.add(body1);
list.add(body2);

Call<ResponseBody> uploadCall = downloadService.uploadFiles(list);

文件和参数混合上传

@Multipart
@POST
Call<ResponseBody> upLoad(@Part MultipartBody.Part file,@Part("id_content") RequestBody body);
File file = new File("E:\\1.jpg");
RequestBody requestFile = RequestBody.create(file, MediaType.parse("image/*"));
MultipartBody.Part body = MultipartBody.Part.createFormData("file_data", file.getName(), requestFile);
RequestBody requestBody = RequestBody.create("12026799",MediaType.parse("text/plain"));

Call<ResponseBody> uploadCall = downloadService.uploadFile(body,requestBody);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值