use

  1. Builder builder = new OkHttpClient().newBuilder()
  2. // 连接池设置
  3. .connectionPool(new ConnectionPool(10, 5, TimeUnit.MINUTES))
  4. // 连接、读写超时设置
  5. .connectTimeout(15, TimeUnit.SECONDS).readTimeout(15, TimeUnit.SECONDS)
  6. .writeTimeout(15, TimeUnit.SECONDS);
  7. builder.addInterceptor(new Interceptor() {
  8. @Override
  9. public Response intercept(Chain chain) throws IOException {
  10. Request request = chain.request();
  11. long startTime = System.nanoTime();
  12. log.info(String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
  13. request.headers()));
  14. Response response = chain.proceed(request);
  15. long endTime = System.nanoTime();
  16. log.info(String.format("Received response for %s in %.1fms %n%s", response.request().url(),
  17. (endTime - startTime) / 1e6d, response.headers()));
  18. return response;
  19. }
  20. });
  21. builder.addInterceptor(new Interceptor() {
  22. @Override
  23. public Response intercept(Chain chain) throws IOException {
  24. Request request = chain.request();
  25. // 统一追加URL参数
  26. HttpUrl.Builder builder = request.url().newBuilder();
  27. HttpUrl newUrl = builder.addQueryParameter("appId", "AutoAdd-appId").build();
  28. // 统一追加header参数
  29. Headers.Builder builderHeaders = request.headers().newBuilder();
  30. builderHeaders.add("user-agent", "AutoAdd-user-agent");
  31. Headers newHeader = builderHeaders.add("header1", "AutoAdd-header1").build();
  32. // 统一追加Body参数
  33. if ("POST" == request.method()) {
  34. request.body().writeTo(sink);
  35. // 构建新Body
  36. // RequestBody newBody =
  37. // RequestBody.create(MediaType.parse("application/json"),
  38. // "{\"token\":\"Auto-newBody\"}");
  39. }
  40. // 利用新的Url 构建新的Request ,并发送给服务器
  41. Request newRequest = request.newBuilder().headers(newHeader).url(newUrl).build();
  42. return chain.proceed(newRequest);
  43. }
  44. });
  45. OkHttpClient httpClient = builder.build();
  46. public static String getResponseString(OkHttpClient client, Request request) throws IOException {
  47. try (Response response = client.newCall(request).execute(); ResponseBody body = response.body()) {
  48. return body.string();
  49. }
  50. }
  51. public static byte[] getResponseBytes(OkHttpClient client, Request request) throws IOException {
  52. try (Response response = client.newCall(request).execute(); ResponseBody body = response.body()) {
  53. return body.bytes();
  54. }
  55. }