From 8368b84a3b3b1cefed8145b2204e51c0dd51776b Mon Sep 17 00:00:00 2001 From: 648540858 <648540858@qq.com> Date: Fri, 25 Nov 2022 11:57:46 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96okhttp=E5=B9=B6=E5=8F=91?= =?UTF-8?q?=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../iot/vmp/media/zlm/ZLMRESTfulUtils.java | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/src/main/java/com/genersoft/iot/vmp/media/zlm/ZLMRESTfulUtils.java b/src/main/java/com/genersoft/iot/vmp/media/zlm/ZLMRESTfulUtils.java index bf9551d4..2815e643 100644 --- a/src/main/java/com/genersoft/iot/vmp/media/zlm/ZLMRESTfulUtils.java +++ b/src/main/java/com/genersoft/iot/vmp/media/zlm/ZLMRESTfulUtils.java @@ -23,27 +23,34 @@ public class ZLMRESTfulUtils { private final static Logger logger = LoggerFactory.getLogger(ZLMRESTfulUtils.class); - - + private OkHttpClient client; public interface RequestCallback{ void run(JSONObject response); } private OkHttpClient getClient(){ - OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); - //todo 暂时写死超时时间 均为5s - httpClientBuilder.connectTimeout(5,TimeUnit.SECONDS); //设置连接超时时间 - httpClientBuilder.readTimeout(5,TimeUnit.SECONDS); //设置读取超时时间 - if (logger.isDebugEnabled()) { - HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> { - logger.debug("http请求参数:" + message); - }); - logging.setLevel(HttpLoggingInterceptor.Level.BASIC); - // OkHttp進行添加攔截器loggingInterceptor - httpClientBuilder.addInterceptor(logging); + if (client == null) { + OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); + //todo 暂时写死超时时间 均为5s + // 设置连接超时时间 + httpClientBuilder.connectTimeout(5,TimeUnit.SECONDS); + // 设置读取超时时间 + httpClientBuilder.readTimeout(5,TimeUnit.SECONDS); + // 设置连接池 + httpClientBuilder.connectionPool(new ConnectionPool(16, 10, TimeUnit.SECONDS)); + if (logger.isDebugEnabled()) { + HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> { + logger.debug("http请求参数:" + message); + }); + logging.setLevel(HttpLoggingInterceptor.Level.BASIC); + // OkHttp進行添加攔截器loggingInterceptor + httpClientBuilder.addInterceptor(logging); + } + client = httpClientBuilder.build(); } - return httpClientBuilder.build(); + return client; + } @@ -164,9 +171,7 @@ public class ZLMRESTfulUtils { .build(); logger.info(request.toString()); try { - OkHttpClient client = new OkHttpClient.Builder() - .readTimeout(10, TimeUnit.SECONDS) - .build(); + OkHttpClient client = getClient(); Response response = client.newCall(request).execute(); if (response.isSuccessful()) { if (targetPath != null) {