http://blog.csdn.net/lmj623565791/article/details/47911083
Okhttp 简介
支持连接同一地址的链接共享同一个 Socket ,通过连接池来减小响应延迟, 还有透明的GZIP压缩, 请求缓存等优势,其核心主要由路由、连接协议、拦截器、代理、安全性认证、连接池及网络适配,拦截器主要是指添加、移除或者转换请求或者回应 头部信息。
主要功能:
1、联网请求文本数据
2、大文件下载
3、大文件上传
4、请求图片
有两种关联方式
1、直接导入 jar 包,然后将 jar 包添加到项目中
2、在 Gradle 中添加: compile 'com.squareup.okhttp3:okhttp:3.4.1'
使用原生的 okhttp 请求网络数据
//使用原生的 okhttp 请求网络数据, get 和 post
OkHttpClient client = new OkhttpClient();
//get 请求,只能在子线程中调用
private String get(String url) throws IOException{
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
//post 请求,可以拿到数据也可以上传,这儿我们是拿数据
public static final MediaType JSON=MediaType.parse("application/json;charset=utf-8");//配置编码
private String post(String url,String json) throws IOException{
RequestBody body=Request.create(JSON,json);
Request request=new Request.Builder()
.url(url)
.post(body)
.build();
Response response = Client.newCall(request).execute();
return response.body().string();
}