引入库:
implementation 'com.squareup.okhttp3:okhttp:3.2.0'
okhttp内部封装功能:
final Dispatcher dispatcher;
final Proxy proxy;
final List<Protocol> protocols;
final List<ConnectionSpec> connectionSpecs;
final List<Interceptor> interceptors;
final List<Interceptor> networkInterceptors;
final ProxySelector proxySelector;
final CookieJar cookieJar;
final Cache cache;
final InternalCache internalCache;
final SocketFactory socketFactory;
final SSLSocketFactory sslSocketFactory;
final TrustRootIndex trustRootIndex;
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;
创建Okhttp对象方式:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.build();
OkHttpClient okHttpClient1 = new OkHttpClient();
get请求:
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.build();
Request request = new Request.Builder()
.url("")
.build();
try {
Response response = okHttpClient.newCall(request).execute();
response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
post请求:
RequestBody requestBody = new FormBody.Builder()
.add("","")
.build();
Request request = new Request.Builder()
.url("")
.addHeader("","")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.readTimeout(20, TimeUnit.SECONDS)
.build();
try {
Response response = okHttpClient.newCall(request).execute();
response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
网友评论