<学习笔记> 小白一枚,空闲时间学习一些比较好用的开源库,记录于此。
第一个就是网络相关的OKHttp。github地址:https://github.com/square/okhttp
the wbesite (类似官网) and the wiki (This wiki is your guide to using, and perhaps contributing to OkHttp.)
OkHttp内部依赖了okio。github地址:https://github.com/square/okio 最新的JAR下载:the latest JAR
简介:
OkHttp is an HTTP client that’s efficient by default:
- HTTP/2 support allows all requests to the same host to share a
socket. - Connection pooling reduces request latency (if HTTP/2 isn’t
available). - Transparent GZIP shrinks download sizes.
- Response caching avoids the network completely for repeat requests.
(支持 SPDY ,共享同一个Socket来处理同一个服务器的所有请求
如果SPDY不可用,则通过连接池来减少请求延时
无缝的支持GZIP来减少数据流量
缓存响应数据来减少重复的网络请求)
OkHttp perseveres when the network is troublesome: it will silently recover from common connection problems. If your service has multiple IP addresses OkHttp will attempt alternate addresses if the first connect fails. This is necessary for IPv4+IPv6 and for services hosted in redundant data centers. OkHttp initiates new connections with modern TLS features (SNI, ALPN), and falls back to TLS 1.0 if the handshake fails.
(OKHttp可以从很多常用的连接问题中自动恢复。如果您的服务器配置了多个IP地址,当第一个IP连接失败的时候,OkHttp会自动尝试下一个IP。OkHttp还处理了代理服务器问题和SSL握手失败问题。)
一、基本使用
GET请求:
okhttp的请求分为同步,异步两种。同步调用的是execute方法,异步的是调用的enqueue方法。
//创建一个OKHttpClient对象
OkHttpClient okHttpClient = new OkHttpClient();
//创建一个Request
Request request = new Request.Builder().url("http://www.baidu.com").build();
//异步进行
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
Log.i("logger", "request failed");
}
@Override
public void onResponse(Response response) throws IOException {
Log.i("logger", "request success");
//异步请求回调的方法不是在主线程中
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_test.setText("This is test...");
}
});
}
});
//同步,由于Android 4.0之后不能再主线程中进行Http请求,所以在子线程中请求
new Thread(new Runnable() {
@Override
public void run() {
try {
Response response = okHttpClient.newCall(request).execute();
if(response.isSuccessful()){
tv_test.setText(response.body().string());
}else {
throw new IOException("Unexpected code"+response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
POST请求:
传的参数为JSON:
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String json = "canshu";
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
传的参数是键值对时:
RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
只是在处理RequestBody时有所不同,同步和异步请求的方法操作和GET请求的相似;
明显看出当我们在开发中需要用到OKHttp来完成网络请求时,如果每次都是创建OKHttpClient,Request ,Call这样的代码会有很大的冗余,并且OKHttp文档中这样说: Most applications can use a single OkHttpClient for all of their HTTP requests, benefiting from a shared response cache, thread pool, connection re-use, etc.简单来说就是在没有特殊情况下,让我们使用一个OKHttpClient来完成开发。这种情况下,将OKHttp封装成一个工具类就很有必要了,有助于我们进行快速准确的开发。我学习的是鸿洋大神封装的工具类代码:Android OKHttp完全解析 ;