4.1 Retrofit 上传文件

1.接口的声明

public interface UploadService {
/**
*
* @param requestBody 上传参数 post
* @param multipartBody 上传多媒体文件 file
* @return
*/
public static String url = "http://yun918.cn";

    @Multipart
    @POST("/study/public/file_upload.php")
    Call<ResponseBody> uploadFile(@Part("key") RequestBody requestBody, @Part MultipartBody.Part multipartBody);
}

2.file的封装

// 1.获取文件路径转换成File
String filePath = Environment.getExternalStorageDirectory() + File.separator + "aa.jpg";
    File file = new File(filePath);
    if (file.exists()) {
    Log.d(TAG, "exists: " + true);
}
// 2 文件类型请求对象
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"),file);

// 3.文件上传 多媒体对象
MultipartBody.Part multipartBody = MultipartBody.Part.createFormData("file",file.getName(),requestBody);

// 4. post普通参数 key (文件夹的名字) img
RequestBody postParams =RequestBody.create(MediaType.parse("text/plain"), "img");


Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(UploadService.url)
    .addConverterFactory(GsonConverterFactory.create())
    .build();
UploadService uploadService = retrofit.create(UploadService.class);

3.Retrofit 和Okhttp 对比

Okhttp:
OKHttp是一款高效的HTTP库,支持连接同一地址的链接共享同一个socket,通过连接池来减小响应延迟,还有透明的GZIP压缩,请求缓存等优势。OkHttp存在以下的特点:
① 支持HTTP2/SPDY
② socket自动选择最好路线,并支持自动重连
③ 拥有自动维护的socket连接池,减少握手次数
④ 拥有队列线程池,轻松写并发
⑤ 拥有Interceptors轻松处理请求与响应(比如透明GZIP压缩,LOGGING)
⑥ 基于Headers的缓存策略
Retrofit:
Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装。把网络请求都交给给了Okhttp,我们只需要通过简单的配置就能使用retrofit来进行网络请求了。Retrofit框架存在的优势:
① Retrofit使用注解方式,大大简化了我们的URL拼写形式,而且注解含义一目了然,简单易懂;
② Retrofit使用简单,结构层次分明,每一步都能清晰的表达出之所以要使用的寓意;
③ Retrofit支持同步和异步执行,使得请求变得异常简单,只要调用enqueue/execute即可完成;
④ Retrofit更大自由度的支持我们自定义的业务逻辑,如自定义Converters。
⑤ Retrofit支持多种文件解析(Gson,Json,XML,Protobuf)
⑥ Retrofit支持RxJava

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值