1
2
3
4
5
6
7
8
9
|
// Base directory recommended by http://stackoverflow.com/a/32752861/400717.
// Guard against null, which is possible according to
// https://groups.google.com/d/msg/android-developers/-694j87eXVU/YYs4b6kextwJ and
// http://stackoverflow.com/q/4441849/400717.
final @Nullable File baseDir = context.getCacheDir();
if (baseDir != null) {
final File cacheDir = new File(baseDir, "HttpResponseCache");
okHttpClient.setCache(new Cache(cacheDir, HTTP_RESPONSE_DISK_CACHE_MAX_SIZE));
}
|
HTTP_RESPONSE_DISK_CACHE_MAX_SIZE
as 10 * 1024 * 1024
, or 10 MB的大小
1
|
okHttpClient.networkInterceptors().add(new StethoInterceptor());
|
1
2
3
4
5
6
7
|
private static OkHttpClient defaultOkHttpClient() {
OkHttpClient client = new OkHttpClient();
client.setConnectTimeout(Utils.DEFAULT_CONNECT_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.setReadTimeout(Utils.DEFAULT_READ_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
client.setWriteTimeout(Utils.DEFAULT_WRITE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
return client;
}
|
1
|
Picasso.with(context).load(...)
|
Picasso.Builder
实例的downloader方法。
1
2
3
4
5
6
7
|
final Picasso picasso = new Picasso.Builder(context)
.downloader(new OkHttpDownloader(okHttpClient))
.build();
// The client should inject this instance whenever it is needed, but replace the singleton
// instance just in case.
Picasso.setSingletonInstance(picasso);
|
1
|
restAdapterBuilder.setClient(new OkClient(httpClient));
|
1
2
3
4
5
6
7
|
@Provides
@Singleton
public OkHttpClient okHttpClient(final Context context, ...) {
final OkHttpClient okHttpClient = new OkHttpClient();
configureClient(okHttpClient, ...);
return okHttpClient;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public final class UserAgentInterceptor implements Interceptor {
private static final String USER_AGENT_HEADER_NAME = "User-Agent";
private final String userAgentHeaderValue;
public UserAgentInterceptor(String userAgentHeaderValue) {
this.userAgentHeaderValue = Preconditions.checkNotNull(userAgentHeaderValue);
}
@Override
public Response intercept(Chain chain) throws IOException {
final Request originalRequest = chain.request();
final Request requestWithUserAgent = originalRequest.newBuilder()
.removeHeader(USER_AGENT_HEADER_NAME)
.addHeader(USER_AGENT_HEADER_NAME, userAgentHeaderValue)
.build();
return chain.proceed(requestWithUserAgent);
}
}
|
applicationId
with Gradle
请注意,如果您的应用程序使用的是WebView,您可以配置使用相同的User-Agent
header值,你可以通过下面方法创建UserAgentInterceptor:
1
2
|
WebSettings settings = webView.getSettings();
settings.setUserAgentString(userAgentHeaderValue);
|
英文原文链接:http://omgitsmgp.com/2015/12/02/effective-okhttp/ 原文链接: https://xiequan.info/%E5%A6%82%E4%BD%95%E9%AB%98%E6%95%88%E7%9A%84%E4%BD%BF%E7%94%A8okhttp/