一、OKHttp3简介
OKHttp是一个处理网络请求的轻量级开源框架,由移动支付Square公司贡献,用于替代HttpUriConnection和Apache HTTPClient,进行http请求,从Android 4.4 开始HttpUrlConnection底层实现采用OKHttp,而HttpClient已经废弃,并且在Android 6.0 API 23 后已被移除。
GitHub:https://github.com/square/okhttp(截止到博客更新时已有 27096 Star)
http://square.github.io/okhttp/
OKHttp功能:
- post,get等请求
- 文件上传下载
- 加载图片
- 支持请求回调,直接返回对象、对象集合
- 支持session的保持
OKHttp优点:
- 支持HTTP2/SPDY(SPDY是Google开发的基于TCP的传输层协议,用以最小化网络延迟,提升网络速度,优化用户的网络使用体验)
- socket自动选择路线,支持重连,拥有自动维护的socket连接池,减少握手次数,减少了请求延迟,共享socket,减少了对服务器的请求次数
- 基于Headers的缓存策略减少重复的网路请求
- 拥有Interceptors轻松处理请求与相应(自动处理GZip压缩)
当然还有很多其他主流框架,每个框架的优缺点不同,应当根据需求选择合适的框架,比如Google推出的Volley,对频繁的、数据量小的网络请求表现较好,而不适合处理大数据量的操作(比如下载文件),Retrofit基于注解,专注于接口封装,相比之下OKHttp性能较高使用灵活,同时也需要我们自己再进行一层封装。
二、OKHttp3使用
首先要添加OKHttp3的依赖
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.squareup.okio:okio:1.14.0'
以登录为例,post方法使用如下
public static String login(String url, String sid, String password) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
FormBody formBody = new FormBody.Builder()
.add("sid", sid)
.add("password", password)
.build();
Log.d("FormBody", formBody.toString());
Request request = new Request.Builder()
.url(url+"/login")
.post(formBody)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
同样get方法形式如下
public static String get(String url) throws IOException{
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
需要注意的是,url前面必须包含 http://,后面跟冒号和端口号
三、OKHttp3下载和上传图片
使用get方法下载图片,返回byte数组
/**
* 下载图片
* @param url
* @param imagePath 图片路径
* @return byte[]
* @throws IOException
*/
public static byte[] downloadImage(String url, String imagePath) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url+"/show?fileName="+imagePath)
.build();
Response response = okHttpClient.newCall(request).execute();
byte[] bytes = response.body().bytes();
return bytes;
}
使用post方法上传图片
/**
* 上传图片
* @param url
* @param imagePath 图片路径
* @return 新图片的路径
* @throws IOException
* @throws JSONException
*/
public static String uploadImage(String url, String imagePath) throws IOException, JSONException {
OkHttpClient okHttpClient = new OkHttpClient();
Log.d("imagePath", imagePath);
File file = new File(imagePath);
RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", imagePath, image)
.build();
Request request = new Request.Builder()
.url(url+"/uploadImage")
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.optString("image");
}