public class OkHttpExample {
public void doSimpleRequest() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://www.baidu.com")
.build();
// 同步请求一个Request
try(Response response = client.newCall(request).execute()) {
System.out.println("reponse header:"+response.headers());
System.out.println("reponse body:"+response.body().string());
Thread.sleep(TimeUnit.MINUTES.toMillis(5));
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
这个例子的主要部分:
- 创建OkHttpClient。
- 调用client.newCall,返回RealCall。
- 调用RealCall.execute方法,返回Response。
接下来的Okhttp学习就围绕这3点慢慢讲了。
对于第一点OkhttpClient,先从OkHttpClient的属性开始。
final Dispatcher dispatcher;
final @Nullable Proxy proxy;
final List<Protocol> protocols;
final List<ConnectionSpec> connectionSpecs;
final List<Interceptor> interceptors;
final List<Interceptor> networkInterceptors;
final EventListener.Factory eventListenerFactory;
final ProxySelector proxySelector;
final CookieJar cookieJar;
final @Nullable Cache cache;
final @Nullable InternalCache internalCache;
final SocketFactory socketFactory;
final @Nullable SSLSocketFactory sslSocketFactory;
final @Nullable CertificateChainCleaner certificateChainCleaner;
final HostnameVerifier hostnameVerifier;
final CertificatePinner certificatePinner;
final Authenticator proxyAuthenticator;
final Authenticator authenticator;
final ConnectionPool connectionPool;
final Dns dns;
final boolean followSslRedirects;
final boolean followRedirects;
final boolean retryOnConnectionFailure;
final int connectTimeout;
final int readTimeout;
final int writeTimeout;
final int pingInterval;
- Dispatcher: 负责管理OkHttpClient所发起的请求调度,内部的具体实现是一个线程池。Dispatcher负责控制每一个host同时最多只能发起5个请求,同时最多只能发起64个请求(5,64是默认参数,可设置)。
- Proxy
- List<Protocol>: 支持的协议,默认为[http1.1,http2.0]。这里如果要自定义,则一定要包括http1.1。
- ConnectionSpec:用来指定Socket的配置,比如当url为https的时候,需要指定TLS的版本号和加密方式。
- interceptors: 位于okhttp自身拦截器之前。
- networkInterceptors:在正式发起网络请求的拦截器之前。
- Cache
- ConnectionPool: 连接池。
- retryOnConnectionFailure。
- connectTimeout,readTimeout,writeTimeout。
后面学习完之后,上面的选项会逐渐补充完整。
下一篇,先讲Dispatcher。