use
Builder builder = new OkHttpClient().newBuilder()
// 连接池设置
.connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES))
// 连接、读写超时设置
.connectTimeout(15, TimeUnit.SECONDS).readTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS);
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.nanoTime();
log.info(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
request.headers()));
Response response = chain.proceed(request);
long endTime = System.nanoTime();
log.info(String.format("Received response for %s in %.1fms %n%s", response.request().url(),
(endTime - startTime) / 1e6d, response.headers()));
return response;
}
});
builder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
// 统一追加URL参数
HttpUrl.Builder builder = request.url().newBuilder();
HttpUrl newUrl = builder.addQueryParameter("appId", "AutoAdd-appId").build();
// 统一追加header参数
Headers.Builder builderHeaders = request.headers().newBuilder();
builderHeaders.add("user-agent", "AutoAdd-user-agent");
Headers newHeader = builderHeaders.add("header1", "AutoAdd-header1").build();
// 统一追加Body参数
if ("POST" == request.method()) {
request.body().writeTo(sink);
// 构建新Body
// RequestBody newBody =
// RequestBody.create(MediaType.parse("application/json"),
// "{\"token\":\"Auto-newBody\"}");
}
// 利用新的Url 构建新的Request ,并发送给服务器
Request newRequest = request.newBuilder().headers(newHeader).url(newUrl).build();
return chain.proceed(newRequest);
}
});
OkHttpClient httpClient = builder.build();
public static String getResponseString(OkHttpClient client, Request request) throws IOException {
try (Response response = client.newCall(request).execute(); ResponseBody body = response.body()) {
return body.string();
}
}
public static byte[] getResponseBytes(OkHttpClient client, Request request) throws IOException {
try (Response response = client.newCall(request).execute(); ResponseBody body = response.body()) {
return body.bytes();
}
}