网络请求
Introduction
笔者没有把

Comparison( 比较)
目前基本上每个应用都会使用
- 能够取消现有的网络请求
- 能够并发请求
- 连接池能够复用存在的
Socket 连接 - 本地对于响应的缓存
- 简单的异步接口来避免主线程阻塞
- 对于
REST API 的封装 - 重连策略
- 能够有效地载入与传输图片
- 支持对于
JSON 的序列化 - 支持
SPDY 、HTTP/2 最早的时候Android 只有两个主要的HTTP 客户端: HttpURLConnection, Apache HTTP Client。根据Google 官方博客的内容,HttpURLConnection 在早期的Android 版本中可能存在一些Bug:
在
Froyo 版本之前,HttpURLConnection 包含了一些很恶心的错误。特别是对于关闭可读的InputStream 时候可能会污染整个连接池。
同样,
Apache HTTP Client 中复杂的API 设计让人们根本不想用它,Android 团队并不能够有效地工作。
而对于大部分普通开发者而言,它们觉得应该根据不同的版本使用不同的客户端。对于
if (stack == null) {
if (Build.VERSION.SDK_INT >= 9) {
stack = new HurlStack();
} else {
// Prior to Gingerbread, HttpUrlConnection was unreliable.
// See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
}
}
不过这样会很让开发者头疼,

HTTP/2 以及SPDY 的支持多路复用- 连接池会降低并发连接数
- 透明
GZIP 加密减少下载体积 - 响应缓存避免大量重复请求
- 同时支持同步的阻塞式调用与异步回调式调用
笔者关于
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, Throwable throwable) {
throwable.printStackTrace();
}
@Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
}
});
}
这个用起来非常方便,因为往往大的数据请求都不能放置在
- Automatic scheduling of network requests.
- Multiple concurrent network connections.
- Transparent disk and memory response caching with standard HTTP cache coherence.
- Support for request prioritization.
- Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
- Ease of customization, for example, for retry and backoff.
- Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
- Debugging and tracing tools.

private static final int DEFAULT_NETWORK_THREAD_POOL_SIZE = 4;
不过
private int maxRequests = 64;
private int maxRequestsPerHost = 5;
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
在某些情况下,
到这里已经可以发现,
public interface GitHubService {
@GET("/users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com")
.build();
GitHubService service = retrofit.create(GitHubService.class);
除此之外,
