wangyunpeng 14 часов назад
Родитель
Сommit
557fece1e5

+ 0 - 86
core/src/main/java/com/tzld/videoVector/config/HttpClientConfig.java

@@ -1,86 +0,0 @@
-package com.tzld.videoVector.config;
-
-import org.apache.http.HttpHost;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
-import org.springframework.context.annotation.Bean;
-import org.springframework.context.annotation.Configuration;
-
-@Configuration
-public class HttpClientConfig {
-
-
-    /**
-     * 链接建立的超时时间 ms
-     */
-    private static final int CONNECTION_TIMEOUT = 5000;
-    /**
-     * 响应超时时间 ms
-     */
-    private static final int SOCKET_TIMEOUT = 30000;
-
-    /**
-     * 每个路由的最大连接数
-     */
-    private static final int MAX_PER_ROUTE = 100;
-
-    /**
-     * 最大连接数
-     */
-    private static final int MAX_TOTAL = 500;
-
-    /**
-     * 重试次数,默认0
-     */
-    private static final int RETRY_COUNT = 3;
-
-    /**
-     * 从connection pool中获得一个connection的超时时间 ms
-     */
-    private static final int CONNECTION_WAIT_TIMEOUT = 5000;
-
-
-    @Bean(name = "httpClient")
-    public CloseableHttpClient httpClient() {
-
-        RequestConfig requestConfig = RequestConfig.custom()
-                .setConnectTimeout(CONNECTION_TIMEOUT)
-                .setSocketTimeout(SOCKET_TIMEOUT)
-                .setConnectionRequestTimeout(CONNECTION_WAIT_TIMEOUT)
-                .build();
-
-        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
-        connectionManager.setMaxTotal(MAX_TOTAL); // 设置最大连接数
-        connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); // 每个路由的最大连接数
-
-        return HttpClientBuilder.create()
-                .setDefaultRequestConfig(requestConfig)
-                .setConnectionManager(connectionManager)
-                .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false))
-                .build();
-    }
-
-    @Bean(name = "proxyHttpClient")
-    public CloseableHttpClient proxyHttpClient() {
-        HttpHost proxy = new HttpHost("121.43.150.231", 3128, "http");
-        RequestConfig requestConfig = RequestConfig.custom()
-                .setConnectTimeout(CONNECTION_TIMEOUT)
-                .setSocketTimeout(SOCKET_TIMEOUT)
-                .setConnectionRequestTimeout(CONNECTION_WAIT_TIMEOUT)
-                .build();
-
-        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
-        connectionManager.setMaxTotal(MAX_TOTAL); // 设置最大连接数
-        connectionManager.setDefaultMaxPerRoute(MAX_PER_ROUTE); // 每个路由的最大连接数
-
-        return HttpClientBuilder.create()
-                .setProxy(proxy)
-                .setDefaultRequestConfig(requestConfig)
-                .setConnectionManager(connectionManager)
-                .setRetryHandler(new DefaultHttpRequestRetryHandler(RETRY_COUNT, false))
-                .build();
-    }
-}

+ 119 - 91
core/src/main/java/com/tzld/videoVector/service/impl/DeconstructServiceImpl.java

@@ -3,13 +3,15 @@ package com.tzld.videoVector.service.impl;
 import com.alibaba.fastjson.JSONObject;
 import com.tzld.videoVector.model.entity.DeconstructResult;
 import com.tzld.videoVector.service.DeconstructService;
-import com.tzld.videoVector.util.http.HttpClientUtils;
-import com.tzld.videoVector.util.http.HttpResponseContent;
 import lombok.extern.slf4j.Slf4j;
+import okhttp3.*;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Service;
 
+import javax.annotation.PostConstruct;
+import java.io.IOException;
 import java.util.List;
+import java.util.concurrent.TimeUnit;
 
 /**
  * 内容解构服务实现类
@@ -18,12 +20,20 @@ import java.util.List;
 @Service
 public class DeconstructServiceImpl implements DeconstructService {
 
+    private OkHttpClient client;
+
     /**
      * 内容解构 API Host
      */
     @Value("${deconstruct.api.host:http://supply-content-deconstruction-api.piaoquantv.com}")
     private String apiHost;
 
+    /**
+     * 请求超时时间(秒)
+     */
+    @Value("${deconstruct.api.timeout:60}")
+    private int timeout;
+
     /**
      * 创建任务接口路径
      */
@@ -34,6 +44,18 @@ public class DeconstructServiceImpl implements DeconstructService {
      */
     private static final String QUERY_RESULT_PATH_TEMPLATE = "/api/v1/content/tasks/%s";
 
+    private static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");
+
+    @PostConstruct
+    public void init() {
+        client = new OkHttpClient.Builder()
+                .connectTimeout(timeout, TimeUnit.SECONDS)
+                .readTimeout(timeout, TimeUnit.SECONDS)
+                .writeTimeout(timeout, TimeUnit.SECONDS)
+                .build();
+        log.info("内容解构服务初始化完成,API地址: {}", apiHost);
+    }
+
     @Override
     public String deconstruct(int scene, int contentType, String channelContentId,
                               String videoUrl, List<String> images,
@@ -61,43 +83,45 @@ public class DeconstructServiceImpl implements DeconstructService {
 
         try {
             // 发送 POST 请求
-            HttpResponseContent response = HttpClientUtils.postRequestBody(
-                    url, 
-                    requestBody, 
-                    null
-            );
-
-            if (response == null) {
-                log.error("调用内容解构 API 失败,响应为空");
-                return null;
+            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, requestBody.toJSONString());
+            Request request = new Request.Builder()
+                    .url(url)
+                    .post(body)
+                    .addHeader("Content-Type", "application/json")
+                    .build();
+
+            try (Response response = client.newCall(request).execute()) {
+                if (!response.isSuccessful()) {
+                    String errorBody = response.body() != null ? response.body().string() : "无";
+                    log.error("调用内容解构 API 失败,HTTP状态码: {}, 错误信息: {}", response.code(), errorBody);
+                    return null;
+                }
+
+                String responseBody = response.body().string();
+                log.info("内容解构 API 响应: {}", responseBody);
+
+                JSONObject jsonResponse = JSONObject.parseObject(responseBody);
+
+                // 检查响应码
+                Integer code = jsonResponse.getInteger("code");
+                if (code == null || code != 0) {
+                    String msg = jsonResponse.getString("msg");
+                    log.error("内容解构 API 调用失败,code: {}, msg: {}", code, msg);
+                    return null;
+                }
+
+                // 提取 taskId
+                JSONObject data = jsonResponse.getJSONObject("data");
+                if (data == null) {
+                    log.error("内容解构 API 响应中 data 为空");
+                    return null;
+                }
+
+                String taskId = data.getString("taskId");
+                log.info("内容解构任务创建成功,taskId: {}", taskId);
+                return taskId;
             }
-
-            // 解析响应
-            String responseBody = response.getBodyContent();
-            log.info("内容解构 API 响应: {}", responseBody);
-
-            JSONObject jsonResponse = JSONObject.parseObject(responseBody);
-            
-            // 检查响应码
-            Integer code = jsonResponse.getInteger("code");
-            if (code == null || code != 0) {
-                String msg = jsonResponse.getString("msg");
-                log.error("内容解构 API 调用失败,code: {}, msg: {}", code, msg);
-                return null;
-            }
-
-            // 提取 taskId
-            JSONObject data = jsonResponse.getJSONObject("data");
-            if (data == null) {
-                log.error("内容解构 API 响应中 data 为空");
-                return null;
-            }
-
-            String taskId = data.getString("taskId");
-            log.info("内容解构任务创建成功,taskId: {}", taskId);
-            return taskId;
-
-        } catch (Exception e) {
+        } catch (IOException e) {
             log.error("调用内容解构 API 异常: {}", e.getMessage(), e);
             return null;
         }
@@ -116,61 +140,65 @@ public class DeconstructServiceImpl implements DeconstructService {
 
         try {
             // 发送 GET 请求
-            HttpResponseContent response = HttpClientUtils.get(url);
-
-            if (response == null) {
-                log.error("查询解构结果失败,响应为空,taskId: {}", taskId);
-                return null;
-            }
-
-            // 解析响应
-            String responseBody = response.getBodyContent();
-            log.info("查询解构结果响应: {}", responseBody);
-
-            JSONObject jsonResponse = JSONObject.parseObject(responseBody);
-
-            DeconstructResult result = new DeconstructResult();
-            result.setTaskId(taskId);
-
-            // 检查响应码
-            Integer code = jsonResponse.getInteger("code");
-            // 其他非成功状态
-            if (code == null || code != 0) {
-                String msg = jsonResponse.getString("msg");
-                log.error("查询解构结果失败,code: {}, msg: {}, taskId: {}", code, msg, taskId);
-                result.setSuccess(false);
-                result.setReason(msg);
+            Request request = new Request.Builder()
+                    .url(url)
+                    .get()
+                    .build();
+
+            try (Response response = client.newCall(request).execute()) {
+                if (!response.isSuccessful()) {
+                    String errorBody = response.body() != null ? response.body().string() : "无";
+                    log.error("查询解构结果失败,HTTP状态码: {}, 错误信息: {}, taskId: {}", response.code(), errorBody, taskId);
+                    return null;
+                }
+
+                String responseBody = response.body().string();
+                log.info("查询解构结果响应: {}", responseBody);
+
+                JSONObject jsonResponse = JSONObject.parseObject(responseBody);
+
+                DeconstructResult result = new DeconstructResult();
+                result.setTaskId(taskId);
+
+                // 检查响应码
+                Integer code = jsonResponse.getInteger("code");
+                // 其他非成功状态
+                if (code == null || code != 0) {
+                    String msg = jsonResponse.getString("msg");
+                    log.error("查询解构结果失败,code: {}, msg: {}, taskId: {}", code, msg, taskId);
+                    result.setSuccess(false);
+                    result.setReason(msg);
+                    return result;
+                }
+
+                // 解析 data
+                JSONObject data = jsonResponse.getJSONObject("data");
+                if (data == null) {
+                    log.error("查询解构结果响应中 data 为空,taskId: {}", taskId);
+                    result.setSuccess(false);
+                    return result;
+                }
+
+                // 填充结果
+                result.setTaskId(data.getString("taskId"));
+                result.setStatus(data.getInteger("status"));
+                result.setResult(data.getString("result"));
+                result.setReason(data.getString("reason"));
+                result.setSuccess(result.getStatus() != null && result.getStatus() == 2);
+
+                // 解析 url 对象
+                JSONObject urlObj = data.getJSONObject("url");
+                if (urlObj != null) {
+                    result.setPointUrl(urlObj.getString("pointUrl"));
+                    result.setWeightUrl(urlObj.getString("weightUrl"));
+                    result.setPatternUrl(urlObj.getString("patternUrl"));
+                }
+
+                log.info("查询解构结果成功,taskId: {}, status: {}, success: {}",
+                        result.getTaskId(), result.getStatusDesc(), result.isSuccess());
                 return result;
             }
-
-            // 解析 data
-            JSONObject data = jsonResponse.getJSONObject("data");
-            if (data == null) {
-                log.error("查询解构结果响应中 data 为空,taskId: {}", taskId);
-                result.setSuccess(false);
-                return result;
-            }
-
-            // 填充结果
-            result.setTaskId(data.getString("taskId"));
-            result.setStatus(data.getInteger("status"));
-            result.setResult(data.getString("result"));
-            result.setReason(data.getString("reason"));
-            result.setSuccess(result.getStatus() != null && result.getStatus() == 2);
-
-            // 解析 url 对象
-            JSONObject urlObj = data.getJSONObject("url");
-            if (urlObj != null) {
-                result.setPointUrl(urlObj.getString("pointUrl"));
-                result.setWeightUrl(urlObj.getString("weightUrl"));
-                result.setPatternUrl(urlObj.getString("patternUrl"));
-            }
-
-            log.info("查询解构结果成功,taskId: {}, status: {}, success: {}", 
-                    result.getTaskId(), result.getStatusDesc(), result.isSuccess());
-            return result;
-
-        } catch (Exception e) {
+        } catch (IOException e) {
             log.error("查询解构结果异常,taskId: {}, error: {}", taskId, e.getMessage(), e);
             return null;
         }

+ 0 - 96
core/src/main/java/com/tzld/videoVector/util/HttpClientFactory.java

@@ -1,96 +0,0 @@
-package com.tzld.videoVector.util;
-
-import com.google.common.collect.Lists;
-import lombok.extern.slf4j.Slf4j;
-import org.apache.commons.lang3.concurrent.BasicThreadFactory;
-import org.apache.http.HttpRequestInterceptor;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.config.Registry;
-import org.apache.http.config.RegistryBuilder;
-import org.apache.http.conn.HttpClientConnectionManager;
-import org.apache.http.conn.socket.ConnectionSocketFactory;
-import org.apache.http.conn.socket.PlainConnectionSocketFactory;
-import org.apache.http.conn.ssl.NoopHostnameVerifier;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
-import org.apache.http.impl.client.HttpClientBuilder;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
-import org.apache.http.ssl.SSLContexts;
-import org.slf4j.MDC;
-
-import javax.net.ssl.SSLContext;
-import java.security.KeyManagementException;
-import java.security.KeyStoreException;
-import java.security.NoSuchAlgorithmException;
-import java.util.List;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-@Slf4j
-public class HttpClientFactory {
-
-    private static final ScheduledExecutorService SCHEDULED_CLOSED_EXECUTOR = new ScheduledThreadPoolExecutor(1,
-            new BasicThreadFactory.Builder().namingPattern("http conn-closed-thread-%s").priority(Thread.NORM_PRIORITY).daemon(false).build(), (r, e) -> log.error(" monitor push reject task error={}", e.toString()));
-
-    private static final List<HttpClientConnectionManager> HTTP_CLIENT_CONNECTION_MANAGERS = Lists.newArrayList();
-
-    static {
-        SCHEDULED_CLOSED_EXECUTOR.schedule(() -> HTTP_CLIENT_CONNECTION_MANAGERS.forEach(HttpClientConnectionManager::closeExpiredConnections), 5, TimeUnit.SECONDS);
-    }
-
-    private static HttpRequestInterceptor getInterceptor() {
-        HttpRequestInterceptor requestInterceptor = (request, context) -> {
-            try {
-                String missSpanId = MDC.get("missSpanId");
-                String missTraceId = MDC.get("request-id");
-                if (missTraceId != null && !"".equals(missTraceId.trim())) {
-                    request.setHeader("request-id", missTraceId);
-                }
-                if (missSpanId != null && !"".equals(missSpanId.trim())) {
-                    request.setHeader("missSpanId", missSpanId);
-                }
-            } catch (Exception e) {
-                log.error(e.getMessage(), e);
-            }
-        };
-        return requestInterceptor;
-    }
-
-    /**
-     * @param connectTimeout 连接超时时间 ms
-     * @param socketTimeout  读超时时间(等待数据超时时间)ms
-     * @param maxPerRoute    每个路由的最大连接数
-     * @param maxTotal       最大连接数
-     * @param retryCount     重试次数
-     * @return httpclient instance
-     */
-    public static CloseableHttpClient create(int connectTimeout, int socketTimeout, int maxPerRoute, int maxTotal,
-                                             int retryCount, int connectionWaitTimeout) {
-        try {
-            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).setConnectionRequestTimeout(connectionWaitTimeout).build();
-            CloseableHttpClient client = HttpClientBuilder.create()
-                    .setDefaultRequestConfig(requestConfig)
-                    .setConnectionManager(createConnectionManager(maxPerRoute, maxTotal))
-                    .setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false)).addInterceptorFirst(getInterceptor()).build();
-            return client;
-        } catch (Throwable e) {
-            log.error("create HttpPoolClient exception", e);
-            throw new RuntimeException("create HttpPoolClient exception");
-        }
-    }
-
-    private static PoolingHttpClientConnectionManager createConnectionManager(int maxPerRoute, int maxTotal) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
-        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true).build();
-        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
-                .register("http", PlainConnectionSocketFactory.getSocketFactory())
-                .register("https", new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE)).build();
-        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
-        cm.setDefaultMaxPerRoute(maxPerRoute);
-        cm.setMaxTotal(maxTotal);
-        HTTP_CLIENT_CONNECTION_MANAGERS.add(cm);
-        return cm;
-    }
-
-}

+ 64 - 33
core/src/main/java/com/tzld/videoVector/util/feishu/FeiShu.java

@@ -3,17 +3,27 @@ package com.tzld.videoVector.util.feishu;
 import com.alibaba.fastjson.JSONObject;
 import com.tzld.videoVector.util.feishu.model.FeishuChatListResult;
 import com.tzld.videoVector.util.feishu.model.FeishuGroup;
-import com.tzld.videoVector.util.http.HttpClientUtils;
-import com.tzld.videoVector.util.http.HttpResponseContent;
+import okhttp3.*;
 import org.slf4j.LoggerFactory;
 import org.springframework.data.util.Pair;
 
+import java.io.IOException;
 import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 public class FeiShu {
 
     private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(FeiShu.class);
 
+    private static final OkHttpClient client = new OkHttpClient.Builder()
+            .connectTimeout(30, TimeUnit.SECONDS)
+            .readTimeout(30, TimeUnit.SECONDS)
+            .writeTimeout(30, TimeUnit.SECONDS)
+            .build();
+
+    private static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");
+
     public static final String URL_FEISHU_ACCESSTOKEN = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal";
     public static final String URL_FEISHU_CHAT_LIST = "https://open.feishu.cn/open-apis/chat/v4/list?page_size=200";
     public static final String URL_FEISHU_SEND_MESSAGE = "https://open.feishu.cn/open-apis/message/v4/send";
@@ -30,15 +40,23 @@ public class FeiShu {
 
         while (retryCount < 3) {
             try {
-                HashMap<String, String> params = new HashMap<>();
-                params.put("app_id", APPID);
-                params.put("app_secret", APPSECRET);
-                HttpResponseContent hrc = HttpClientUtils.postForm(URL_FEISHU_ACCESSTOKEN, params, new HashMap<>());
-                LOGGER.info("feishu accessToken response = {}", hrc.getBodyContent());
-                JSONObject response = JSONObject.parseObject(hrc.getBodyContent());
-                String accessToken = response.getString("tenant_access_token");
-                int expireSeconds = response.getIntValue("expire");
-                return Pair.of(accessToken, expireSeconds);
+                FormBody.Builder formBuilder = new FormBody.Builder();
+                formBuilder.add("app_id", APPID);
+                formBuilder.add("app_secret", APPSECRET);
+
+                Request request = new Request.Builder()
+                        .url(URL_FEISHU_ACCESSTOKEN)
+                        .post(formBuilder.build())
+                        .build();
+
+                try (Response response = client.newCall(request).execute()) {
+                    String responseBody = response.body() != null ? response.body().string() : "";
+                    LOGGER.info("feishu accessToken response = {}", responseBody);
+                    JSONObject jsonResponse = JSONObject.parseObject(responseBody);
+                    String accessToken = jsonResponse.getString("tenant_access_token");
+                    int expireSeconds = jsonResponse.getIntValue("expire");
+                    return Pair.of(accessToken, expireSeconds);
+                }
             } catch (Exception e) {
                 LOGGER.error("requestFeishuAccessToken, error ,retryCount = {}, cost = {}", retryCount, System.currentTimeMillis() - startTime, e);
             }
@@ -49,28 +67,41 @@ public class FeiShu {
 
     }
 
-    public static void main(String[] args) {
-        HashMap<String, String> params = new HashMap<>();
-        params.put("app_id", APPID);
-        params.put("app_secret", APPSECRET);
-        HttpResponseContent hrc = HttpClientUtils.postForm(URL_FEISHU_ACCESSTOKEN, params, new HashMap<>());
-        System.out.println(hrc.getBodyContent());
-        JSONObject response = JSONObject.parseObject(hrc.getBodyContent());
-        String accessToken = response.getString("tenant_access_token");
-
-        HashMap<String, String> header = new HashMap<>();
-        header.put("Authorization", "Bearer " + accessToken);
-        header.put("content-type", "application/json; charset=utf-8");
-
-        //获取群聊ID
-        HttpResponseContent chatHrc = HttpClientUtils.get(URL_FEISHU_CHAT_LIST, header);
-        JSONObject responseJSON = JSONObject.parseObject(chatHrc.getBodyContent());
-        String chatData = responseJSON.getString("data");
-        System.out.println(chatData);
-        System.out.println("-------------------");
-        FeishuChatListResult feishuChatListResult = JSONObject.parseObject(chatData, FeishuChatListResult.class);
-        for (FeishuGroup group : feishuChatListResult.getGroups()) {
-            System.out.println(JSONObject.toJSONString(group));
+    public static void main(String[] args) throws IOException {
+        FormBody.Builder formBuilder = new FormBody.Builder();
+        formBuilder.add("app_id", APPID);
+        formBuilder.add("app_secret", APPSECRET);
+
+        Request tokenRequest = new Request.Builder()
+                .url(URL_FEISHU_ACCESSTOKEN)
+                .post(formBuilder.build())
+                .build();
+
+        try (Response tokenResponse = client.newCall(tokenRequest).execute()) {
+            String tokenBody = tokenResponse.body() != null ? tokenResponse.body().string() : "";
+            System.out.println(tokenBody);
+            JSONObject response = JSONObject.parseObject(tokenBody);
+            String accessToken = response.getString("tenant_access_token");
+
+            //获取群聊ID
+            Request chatRequest = new Request.Builder()
+                    .url(URL_FEISHU_CHAT_LIST)
+                    .get()
+                    .addHeader("Authorization", "Bearer " + accessToken)
+                    .addHeader("Content-Type", "application/json; charset=utf-8")
+                    .build();
+
+            try (Response chatResponse = client.newCall(chatRequest).execute()) {
+                String chatBody = chatResponse.body() != null ? chatResponse.body().string() : "";
+                JSONObject responseJSON = JSONObject.parseObject(chatBody);
+                String chatData = responseJSON.getString("data");
+                System.out.println(chatData);
+                System.out.println("-------------------");
+                FeishuChatListResult feishuChatListResult = JSONObject.parseObject(chatData, FeishuChatListResult.class);
+                for (FeishuGroup group : feishuChatListResult.getGroups()) {
+                    System.out.println(JSONObject.toJSONString(group));
+                }
+            }
         }
     }
 }

+ 35 - 28
core/src/main/java/com/tzld/videoVector/util/feishu/FeishuMessageSender.java

@@ -1,8 +1,6 @@
 package com.tzld.videoVector.util.feishu;
 
 import com.alibaba.fastjson.JSONObject;
-import com.tzld.videoVector.util.HttpClientFactory;
-import com.tzld.videoVector.util.MapBuilder;
 import com.tzld.videoVector.util.feishu.model.Message;
 import com.tzld.videoVector.util.feishu.model.MessageParams;
 import com.tzld.videoVector.util.feishu.model.config.MessageConfig;
@@ -12,16 +10,8 @@ import com.tzld.videoVector.util.feishu.model.element.Filed;
 import com.tzld.videoVector.util.feishu.model.element.MarkDownText;
 import com.tzld.videoVector.util.feishu.model.header.HeadTitle;
 import com.tzld.videoVector.util.feishu.model.header.MessageHeader;
-import com.tzld.videoVector.util.http.HttpClientUtils;
-import com.tzld.videoVector.util.http.HttpResponseContent;
 import lombok.extern.slf4j.Slf4j;
-import org.apache.http.HttpEntity;
-import org.apache.http.StatusLine;
-import org.apache.http.client.methods.CloseableHttpResponse;
-import org.apache.http.client.methods.HttpPost;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.util.EntityUtils;
+import okhttp3.*;
 import org.apache.http.util.TextUtils;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.InitializingBean;
@@ -29,8 +19,9 @@ import org.springframework.beans.factory.annotation.Value;
 import org.springframework.data.util.Pair;
 import org.springframework.stereotype.Component;
 
-import java.nio.charset.StandardCharsets;
+import java.io.IOException;
 import java.util.*;
+import java.util.concurrent.TimeUnit;
 
 @Component
 @Slf4j
@@ -40,8 +31,13 @@ public class FeishuMessageSender implements InitializingBean {
 
     private static final String webHookUrl = "https://open.feishu.cn/open-apis/bot/v2/hook/";
 
-    private static final CloseableHttpClient client = HttpClientFactory.create(
-            1000, 1000, 200, 200, 0, 1000);
+    private static final OkHttpClient client = new OkHttpClient.Builder()
+            .connectTimeout(30, TimeUnit.SECONDS)
+            .readTimeout(30, TimeUnit.SECONDS)
+            .writeTimeout(30, TimeUnit.SECONDS)
+            .build();
+
+    private static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");
 
     private static String staticEnv;
 
@@ -60,9 +56,6 @@ public class FeishuMessageSender implements InitializingBean {
     public void sendChat(String chatId, String userOpenId, String title, Map<String, String> infos) {
         try {
             Pair<String, Integer> token = FeiShu.requestAccessToken();
-            HashMap<String, String> header = new HashMap<>();
-            header.put("Authorization", "Bearer " + token.getFirst());
-            header.put("content-type", "application/json; charset=utf-8");
 
             MessageConfig messageConfig = new MessageConfig();
             MessageHeader messageHeader = new MessageHeader();
@@ -78,7 +71,21 @@ public class FeishuMessageSender implements InitializingBean {
             }
             elements.add(textElement);
             MessageParams messageParams = new MessageParams(chatId, userOpenId, new Message(messageConfig, messageHeader, elements));
-            HttpResponseContent hrc = HttpClientUtils.postRequestBody(FeiShu.URL_FEISHU_SEND_MESSAGE, messageParams, header);
+
+            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, JSONObject.toJSONString(messageParams));
+            Request request = new Request.Builder()
+                    .url(FeiShu.URL_FEISHU_SEND_MESSAGE)
+                    .post(body)
+                    .addHeader("Authorization", "Bearer " + token.getFirst())
+                    .addHeader("Content-Type", "application/json; charset=utf-8")
+                    .build();
+
+            try (Response response = client.newCall(request).execute()) {
+                if (!response.isSuccessful()) {
+                    String errorBody = response.body() != null ? response.body().string() : "无";
+                    LOGGER.error("发送飞书消息失败,HTTP状态码: {}, 错误信息: {}", response.code(), errorBody);
+                }
+            }
         } catch (Exception e) {
             LOGGER.error("FeishuMessageSender", e);
         }
@@ -124,16 +131,16 @@ public class FeishuMessageSender implements InitializingBean {
     public static String request(JSONObject bodyParam, String webhookUrl) {
         long start = System.currentTimeMillis();
         try {
-            HttpPost httpPost = new HttpPost(webhookUrl);
-            StringEntity stringEntity = new StringEntity(bodyParam.toJSONString(), StandardCharsets.UTF_8);
-            httpPost.setHeader("Content-Type", "application/json");
-            httpPost.setEntity(stringEntity);
-            CloseableHttpResponse response = client.execute(httpPost);
-            StatusLine statusLine = response.getStatusLine();
-            if (statusLine.getStatusCode() == 200) {
-                HttpEntity responseEntity = response.getEntity();
-                if (Objects.nonNull(responseEntity)) {
-                    return EntityUtils.toString(responseEntity, "UTF-8");
+            RequestBody body = RequestBody.create(JSON_MEDIA_TYPE, bodyParam.toJSONString());
+            Request request = new Request.Builder()
+                    .url(webhookUrl)
+                    .post(body)
+                    .addHeader("Content-Type", "application/json")
+                    .build();
+
+            try (Response response = client.newCall(request).execute()) {
+                if (response.isSuccessful() && response.body() != null) {
+                    return response.body().string();
                 }
             }
         } catch (Exception e) {

+ 0 - 764
core/src/main/java/com/tzld/videoVector/util/http/HttpClientUtils.java

@@ -1,764 +0,0 @@
-package com.tzld.videoVector.util.http;
-
-import com.alibaba.fastjson.JSONObject;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.apache.http.Consts;
-import org.apache.http.HttpEntity;
-import org.apache.http.HttpHeaders;
-import org.apache.http.NameValuePair;
-import org.apache.http.client.config.RequestConfig;
-import org.apache.http.client.entity.UrlEncodedFormEntity;
-import org.apache.http.client.methods.*;
-import org.apache.http.config.*;
-import org.apache.http.conn.socket.ConnectionSocketFactory;
-import org.apache.http.conn.socket.PlainConnectionSocketFactory;
-import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
-import org.apache.http.entity.ByteArrayEntity;
-import org.apache.http.entity.ContentType;
-import org.apache.http.entity.StringEntity;
-import org.apache.http.entity.mime.HttpMultipartMode;
-import org.apache.http.entity.mime.MultipartEntityBuilder;
-import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
-import org.apache.http.message.BasicNameValuePair;
-import org.apache.http.ssl.SSLContexts;
-import org.apache.http.util.EntityUtils;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.TrustManager;
-import javax.net.ssl.X509TrustManager;
-import java.io.File;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.nio.charset.CodingErrorAction;
-import java.security.KeyManagementException;
-import java.security.cert.CertificateException;
-import java.security.cert.X509Certificate;
-import java.util.*;
-import java.util.Map.Entry;
-
-/**
- * 基于apache httpclient4.5.5 的HTTP工具类
- */
-public class HttpClientUtils {
-
-    static Log log = LogFactory.getLog(HttpClientUtils.class);
-
-    private static CloseableHttpClient client;
-    private static RequestConfig requestConfigDefault;
-    private static PoolingHttpClientConnectionManager connManager = null;
-    // 默认请求获取数据的超时时间
-    private static Integer readTimeoutDefault = 150000;
-    // 默认连接超时时间
-    private static Integer connectTimeoutDefault = 50000;
-    // 默认从connectManager获取Connection超时时间
-    private static Integer getConnectionTimeoutDefault = 1000;
-    // 默认的字符集
-    private static String charsetDefault = "UTF-8";
-
-    public static final String contentTypeJson = "application/json";
-    public static final String contentTypeXml = "application/xml";
-
-    private enum MethodType {
-        GET, POST
-    }
-
-    static {
-        try {
-            SSLContext sslContext = SSLContexts.createDefault();
-            sslContext.init(null, new TrustManager[]{new X509TrustManager() {
-
-                public void checkClientTrusted(X509Certificate[] arg0, String arg1)
-                        throws CertificateException {
-                }
-
-                public void checkServerTrusted(X509Certificate[] arg0, String arg1)
-                        throws CertificateException {
-                }
-
-                public X509Certificate[] getAcceptedIssuers() {
-                    return null;
-                }
-            }}, null);
-            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
-                    .register("http", PlainConnectionSocketFactory.INSTANCE)
-                    .register("https", new SSLConnectionSocketFactory(sslContext)).build();
-            connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
-            SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
-            connManager.setDefaultSocketConfig(socketConfig);
-            MessageConstraints messageConstraints = MessageConstraints.custom().build();
-            ConnectionConfig connectionConfig = ConnectionConfig.custom()
-                    .setMalformedInputAction(CodingErrorAction.IGNORE)
-                    .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
-                    .setMessageConstraints(messageConstraints).build();
-            connManager.setDefaultConnectionConfig(connectionConfig);
-            connManager.setMaxTotal(1000);
-            connManager.setDefaultMaxPerRoute(500);
-            connManager.setValidateAfterInactivity(3000);
-        } catch (KeyManagementException e) {
-            log.error(e);
-        }
-
-        requestConfigDefault = RequestConfig.custom().setConnectionRequestTimeout(getConnectionTimeoutDefault)
-                .setConnectTimeout(connectTimeoutDefault).setSocketTimeout(readTimeoutDefault).build();
-        client = HttpClients.custom().useSystemProperties().setConnectionManager(connManager).setDefaultRequestConfig(requestConfigDefault)
-                .build();
-
-    }
-
-
-    public static HttpResponseContent head(String url) {
-        HttpRequestBase request = new HttpHead(url);
-        HttpResponseContent hrc = executeHeadHttpRequest(request, connectTimeoutDefault, readTimeoutDefault);
-        return hrc;
-    }
-
-    /**
-     * get请求
-     *
-     * @param url 请求的url
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent get(String url) {
-        return get(url, null, connectTimeoutDefault, readTimeoutDefault, null);
-    }
-
-    /**
-     * @param url     请求的url
-     * @param headers 请求需要携带的header信息
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent get(String url, Map<String, String> headers) {
-        return get(url, null, connectTimeoutDefault, readTimeoutDefault, headers);
-    }
-
-    /**
-     * get请求
-     *
-     * @param url         请求的url
-     * @param contentType contentType,例如:text/plain
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent get(String url, String contentType) {
-        return get(url, contentType, connectTimeoutDefault, readTimeoutDefault, null);
-    }
-
-    /**
-     * get请求
-     *
-     * @param url            请求的url
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent get(String url, int connectTimeout, int readTimeout) {
-        return get(url, null, connectTimeout, readTimeout, null);
-    }
-
-    /**
-     * get请求
-     *
-     * @param url            请求的url
-     * @param contentType    contentType,例如:text/plain
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @param headers        请求需要携带的header信息
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent get(String url, String contentType, int connectTimeout, int readTimeout, Map<String, String> headers) {
-        return getOrPostUrl(MethodType.GET, url, contentType, connectTimeout, readTimeout, headers);
-    }
-
-    /**
-     * post请求,参数在url中
-     *
-     * @param url 请求的url
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postUrl(String url) {
-        return postUrl(url, null, connectTimeoutDefault, readTimeoutDefault);
-    }
-
-    /**
-     * post请求,参数在url中
-     *
-     * @param url         请求的url
-     * @param contentType contentType,例如:text/plain
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postUrl(String url, String contentType) {
-        return postUrl(url, contentType, connectTimeoutDefault, readTimeoutDefault);
-    }
-
-    /**
-     * post请求,参数在url中
-     *
-     * @param url            请求的url
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postUrl(String url, int connectTimeout, int readTimeout) {
-        return postUrl(url, null, connectTimeout, readTimeout);
-    }
-
-    /**
-     * post请求,参数在url中
-     *
-     * @param url            请求的url
-     * @param contentType    contentType,例如:text/plain
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postUrl(String url, String contentType, int connectTimeout, int readTimeout) {
-        return getOrPostUrl(MethodType.POST, url, contentType, connectTimeout, readTimeout);
-    }
-
-    /**
-     * get或者post请求,参数在url中
-     *
-     * @param methodType     GET/POST
-     * @param url            请求的url
-     * @param contentType    contentType,例如:text/plain
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    private static HttpResponseContent getOrPostUrl(MethodType methodType, String url, String contentType,
-                                                    int connectTimeout, int readTimeout) {
-        return getOrPostUrl(methodType, url, contentType, connectTimeout, readTimeout, null);
-    }
-
-    private static HttpResponseContent getOrPostUrl(MethodType methodType, String url, String contentType,
-                                                    int connectTimeout, int readTimeout, Map<String, String> extHeaders) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        if (methodType == MethodType.GET) {
-            request = new HttpGet(url);
-        } else {
-            request = new HttpPost(url);
-        }
-        // 设置contentType
-        if (contentType != null) {
-            request.addHeader(HttpHeaders.CONTENT_TYPE, contentType);
-        }
-        //add by nieqi since 2022-3-23
-        if (Objects.nonNull(extHeaders)) {
-            for (String s : extHeaders.keySet()) {
-                if (Objects.nonNull(s)) {
-                    String headerValue = extHeaders.get(s);
-                    if (Objects.nonNull(headerValue)) {
-                        request.addHeader(s, headerValue);
-                    }
-                }
-            }
-        }
-        hrc = executeHttpRequest(request, connectTimeout, readTimeout);
-        return hrc;
-    }
-
-    /**
-     * post请求,请求数据在data中
-     *
-     * @param url  请求的url
-     * @param data 请求数据
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postData(String url, String data) {
-        return postData(url, data, null, connectTimeoutDefault, readTimeoutDefault);
-
-    }
-
-    /**
-     * post请求,请求数据在data中
-     *
-     * @param url         请求的url
-     * @param data        请求数据
-     * @param contentType contentType,例如:text/plain
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postData(String url, String data, String contentType) {
-        return postData(url, data, contentType, connectTimeoutDefault, readTimeoutDefault);
-    }
-
-    /**
-     * post请求,请求数据在data中
-     *
-     * @param url            请求的url
-     * @param data           请求数据
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postData(String url, String data, int connectTimeout, int readTimeout) {
-        return postData(url, data, null, connectTimeout, readTimeout);
-    }
-
-    /**
-     * post请求,请求数据在data中
-     *
-     * @param url            请求的url
-     * @param data           请求数据
-     * @param contentType    contentType,例如:text/plain
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postData(String url, String data, String contentType, int connectTimeout,
-                                               int readTimeout) {
-        Map<String, String> headerMap = new HashMap<String, String>();
-        headerMap.put(HttpHeaders.CONTENT_TYPE, contentType);
-        return postDataAddHeader(url, data, headerMap, connectTimeout, readTimeout);
-
-    }
-
-    /**
-     * post请求,请求数据在data中
-     *
-     * @param url            请求的url
-     * @param data           请求数据
-     * @param headerMap      http请求头,key-value放在map中
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postDataAddHeader(String url, String data, Map<String, String> headerMap,
-                                                        int connectTimeout, int readTimeout) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPost httpPost = new HttpPost(url);
-        httpPost.setEntity(new StringEntity(data, charsetDefault));
-        request = httpPost;
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                request.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        hrc = executeHttpRequest(request, connectTimeout, readTimeout);
-        return hrc;
-
-    }
-
-    /**
-     * post请求,请求数据在data中
-     *
-     * @param url            请求的url
-     * @param msgpackBytes   请求数据
-     * @param headerMap      http请求头,key-value放在map中
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postMsgpackDataAddHeader(String url, byte[] msgpackBytes, Map<String, String> headerMap,
-                                                        int connectTimeout, int readTimeout) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPost httpPost = new HttpPost(url);
-        ByteArrayEntity entity = new ByteArrayEntity(msgpackBytes);
-        entity.setContentType("application/msgpack");
-        httpPost.setEntity(entity);
-        request = httpPost;
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                request.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        hrc = executeHttpRequest(request, connectTimeout, readTimeout);
-        return hrc;
-
-    }
-
-    /**
-     * post请求,form表单,不能包含二进制数据
-     *
-     * @param url       请求的url
-     * @param paramsMap form表单参数map
-     * @param headerMap form表单header
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postForm(String url, Map<String, String> paramsMap, Map<String, String> headerMap) {
-        return postForm(url, paramsMap, connectTimeoutDefault, readTimeoutDefault, headerMap);
-    }
-
-    /**
-     * post请求,form表单,不能包含二进制数据
-     *
-     * @param url            请求的url
-     * @param paramsMap      form表单参数map
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @param headerMap      form表单header
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postForm(String url, Map<String, String> paramsMap, int connectTimeout,
-                                               int readTimeout, Map<String, String> headerMap) {
-        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
-        if (Objects.nonNull(paramsMap)) {
-            Iterator<String> iterator = paramsMap.keySet().iterator();
-            while (iterator.hasNext()) {
-                String key = iterator.next();
-                Object value = paramsMap.get(key);
-                nvps.add(new BasicNameValuePair(key, String.valueOf(value)));
-            }
-        }
-        return postForm(url, nvps, connectTimeout, readTimeout, headerMap);
-    }
-
-    /**
-     * post请求,form表单,不能包含二进制数据
-     *
-     * @param url            请求的url
-     * @param nvps           form表单参数
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @param headerMap      form表单header
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postForm(String url, List<NameValuePair> nvps, int connectTimeout,
-                                               int readTimeout, Map<String, String> headerMap) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPost httpPost = new HttpPost(url);
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                httpPost.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        try {
-            httpPost.setEntity(new UrlEncodedFormEntity(nvps, charsetDefault));
-        } catch (UnsupportedEncodingException e) {
-            log.error(e);
-        }
-        request = httpPost;
-        hrc = executeHttpRequest(request, connectTimeout, readTimeout);
-        return hrc;
-    }
-
-    /**
-     * post请求,multipart,支持File,byte[]这两种二进制数据
-     *
-     * @param url       请求的url
-     * @param paramsMap 请求参数map
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postMultipart(String url, Map<String, Object> paramsMap) {
-        return postMultipart(url, paramsMap, connectTimeoutDefault, readTimeoutDefault, null);
-    }
-
-    public static HttpResponseContent postMultipart(String url, Map<String, Object> paramsMap, Map<String, String> headerMap) {
-        return postMultipart(url, paramsMap, connectTimeoutDefault, readTimeoutDefault, headerMap);
-    }
-
-    /**
-     * post请求,multipart,支持File,byte[]这两种二进制数据
-     *
-     * @param url            请求的url
-     * @param paramsMap      请求参数map
-     * @param connectTimeout 连接超时设置,毫秒
-     * @param readTimeout    读取超时设置,毫秒
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    public static HttpResponseContent postMultipart(String url, Map<String, Object> paramsMap, int connectTimeout,
-                                                    int readTimeout, Map<String, String> headerMap) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPost httpPost = new HttpPost(url);
-        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
-        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
-        Iterator<String> iterator = paramsMap.keySet().iterator();
-        while (iterator.hasNext()) {
-            String key = iterator.next();
-            Object value = paramsMap.get(key);
-            if (value instanceof File) {
-                multipartEntityBuilder.addBinaryBody(key, (File) value);
-            } else if (value instanceof byte[]) {
-                multipartEntityBuilder.addBinaryBody(key, (byte[]) value);
-            } else {
-                multipartEntityBuilder.addTextBody(key, String.valueOf(value),
-                        ContentType.create("text/plain", charsetDefault));
-            }
-        }
-        httpPost.setEntity(multipartEntityBuilder.build());
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                httpPost.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        request = httpPost;
-        hrc = executeHttpRequest(request, connectTimeout, readTimeout);
-        return hrc;
-    }
-
-    public static HttpResponseContent postRequestBody(String url, Object s, Map<String, String> headerMap) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPost httpPost = new HttpPost(url);
-
-        StringEntity stringEntity = new StringEntity((s instanceof String) ? (String) s : JSONObject.toJSONString(s), Consts.UTF_8);
-        stringEntity.setContentEncoding(Consts.UTF_8.name());
-        stringEntity.setContentType("application/json");
-        httpPost.setEntity(stringEntity);
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                httpPost.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        request = httpPost;
-        hrc = executeHttpRequest(request, connectTimeoutDefault, readTimeoutDefault);
-        return hrc;
-    }
-
-    public static HttpResponseContent patchRequestBody(String url, Object s, Map<String, String> headerMap) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPatch httpPost = new HttpPatch(url);
-
-        StringEntity stringEntity = new StringEntity((s instanceof String) ? (String) s : JSONObject.toJSONString(s), Consts.UTF_8);
-        stringEntity.setContentEncoding(Consts.UTF_8.name());
-        stringEntity.setContentType("application/json");
-        httpPost.setEntity(stringEntity);
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                httpPost.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        request = httpPost;
-        hrc = executeHttpRequest(request, connectTimeoutDefault, readTimeoutDefault);
-        return hrc;
-    }
-
-    public static HttpResponseContent deleteRequestBody(String url, Object s, HashMap<String, String> headerMap) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpDeleteExpand httpDelete = new HttpDeleteExpand(url);
-
-        StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(s), Consts.UTF_8);
-        stringEntity.setContentEncoding(Consts.UTF_8.name());
-        stringEntity.setContentType("application/json");
-        httpDelete.setEntity(stringEntity);
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                httpDelete.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        request = httpDelete;
-        hrc = executeHttpRequest(request, connectTimeoutDefault, readTimeoutDefault);
-        return hrc;
-    }
-
-    public static HttpResponseContent putRequestBody(String url, Object s, HashMap<String, String> headerMap) {
-        HttpRequestBase request = null;
-        HttpResponseContent hrc = null;
-        HttpPut httpPut = new HttpPut(url);
-
-        StringEntity stringEntity = new StringEntity(JSONObject.toJSONString(s), Consts.UTF_8);
-        stringEntity.setContentEncoding(Consts.UTF_8.name());
-        stringEntity.setContentType("application/json");
-        httpPut.setEntity(stringEntity);
-        // 设置header
-        if (headerMap != null) {
-            for (Entry<String, String> entry : headerMap.entrySet()) {
-                httpPut.addHeader(entry.getKey(), entry.getValue());
-            }
-        }
-        request = httpPut;
-        hrc = executeHttpRequest(request, connectTimeoutDefault, readTimeoutDefault);
-        return hrc;
-    }
-
-    /**
-     * 执行Http请求
-     *
-     * @param request
-     * @param connectTimeout
-     * @param readTimeout
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    private static HttpResponseContent executeHttpRequest(HttpRequestBase request, int connectTimeout,
-                                                          int readTimeout) {
-        CloseableHttpResponse response = null;
-        HttpResponseContent hrc = null;
-        try {
-            // 设置请求配置
-            RequestConfig.Builder configBuilder = RequestConfig.custom();
-            // 设置连接超时
-            configBuilder.setConnectTimeout(connectTimeout);
-            // 设置读取超时
-            configBuilder.setSocketTimeout(readTimeout);
-            // 设置从连接池获取连接实例的超时
-            configBuilder.setConnectionRequestTimeout(getConnectionTimeoutDefault);
-            RequestConfig requestConfig = configBuilder.build();
-            request.setConfig(requestConfig);
-            log.debug("开始执行Http请求, uri:" + request.getURI());
-            response = client.execute(request);
-            hrc = getHttpResponseContent(response);
-            return hrc;
-        } catch (Exception e) {
-            log.error("执行Http请求异常, uri:" + request.getURI(), e);
-        } finally {
-            close(request, response);
-        }
-        return hrc;
-
-    }
-
-    /**
-     * 封装HTTP响应报文
-     *
-     * @param response
-     * @return
-     */
-    private static HttpResponseContent getHttpResponseContent(CloseableHttpResponse response) {
-        // 获取响应实体
-        HttpEntity entity = response.getEntity();
-        if (entity == null) {
-            return null;
-        }
-        HttpResponseContent hrc = new HttpResponseContent();
-        hrc.setHeaders(response.getAllHeaders());
-        hrc.setStatusCode(response.getStatusLine().getStatusCode());
-        ContentType contentType = ContentType.getOrDefault(entity);
-        hrc.setMimeType(contentType.getMimeType());
-        if (contentType.getCharset() != null) {
-            hrc.setCharsetName(contentType.getCharset().name());
-        }
-        try {
-            hrc.setContentBytes(EntityUtils.toByteArray(entity));
-        } catch (IOException e) {
-            log.error("封装HTTP响应报文异常", e);
-        }
-        return hrc;
-
-    }
-
-    /**
-     * 执行Http请求
-     *
-     * @param request
-     * @param connectTimeout
-     * @param readTimeout
-     * @return HttpResponseContent对象,如果http请求出现异常,返回null
-     */
-    private static HttpResponseContent executeHeadHttpRequest(HttpRequestBase request, int connectTimeout,
-                                                          int readTimeout) {
-        CloseableHttpResponse response = null;
-        HttpResponseContent hrc = null;
-        try {
-            // 设置请求配置
-            RequestConfig.Builder configBuilder = RequestConfig.custom();
-            // 设置连接超时
-            configBuilder.setConnectTimeout(connectTimeout);
-            // 设置读取超时
-            configBuilder.setSocketTimeout(readTimeout);
-            // 设置从连接池获取连接实例的超时
-            configBuilder.setConnectionRequestTimeout(getConnectionTimeoutDefault);
-            RequestConfig requestConfig = configBuilder.build();
-            request.setConfig(requestConfig);
-            log.debug("开始执行Http请求, uri:" + request.getURI());
-            response = client.execute(request);
-            hrc = getHeadHttpResponseContent(response);
-            return hrc;
-        } catch (Exception e) {
-            log.error("执行Http请求异常, uri:" + request.getURI(), e);
-        } finally {
-            close(request, response);
-        }
-        return hrc;
-
-    }
-
-    /**
-     * 封装HTTP响应报文
-     *
-     * @param response
-     * @return
-     */
-    private static HttpResponseContent getHeadHttpResponseContent(CloseableHttpResponse response) {
-        HttpResponseContent hrc = new HttpResponseContent();
-        hrc.setHeaders(response.getAllHeaders());
-        hrc.setStatusCode(response.getStatusLine().getStatusCode());
-        HttpEntity entity = response.getEntity();
-        if (entity != null) {
-            ContentType contentType = ContentType.getOrDefault(entity);
-            hrc.setMimeType(contentType.getMimeType());
-            if (contentType.getCharset() != null) {
-                hrc.setCharsetName(contentType.getCharset().name());
-            }
-            try {
-                hrc.setContentBytes(EntityUtils.toByteArray(entity));
-            } catch (IOException e) {
-                log.error("封装HTTP响应报文异常", e);
-            }
-        }
-
-        return hrc;
-
-    }
-
-    /**
-     * 关闭资源
-     *
-     * @param request
-     * @param response
-     */
-    private static void close(HttpRequestBase request, CloseableHttpResponse response) {
-        try {
-            if (request != null)
-                request.releaseConnection();
-            if (response != null)
-                response.close();
-        } catch (Exception e) {
-            log.error("关闭资源异常", e);
-        }
-    }
-
-    /**
-     * url编码
-     *
-     * @param url
-     * @param charset
-     * @return
-     */
-    public static String encodeURL(String url, String charset) {
-        if (url == null || charset == null) {
-            return null;
-        }
-        int p = url.indexOf("?");
-        if (p < 0) {
-            return url;
-        }
-        StringBuilder sb = new StringBuilder();
-        String preStr = url.substring(0, p + 1);
-        sb.append(preStr);
-        String queryStr = url.substring(p + 1, url.length());
-        String[] array = queryStr.split("&");
-        for (int i = 0; i < array.length; i++) {
-            String str = array[i];
-            int pp = str.indexOf("=");
-            if (pp > -1) {
-                sb.append(str.substring(0, pp + 1));
-                try {
-                    sb.append(URLEncoder.encode(str.substring(pp + 1, str.length()), charset));
-                } catch (UnsupportedEncodingException e) {
-                    e.printStackTrace();
-                }
-                if (i < array.length - 1) {
-                    sb.append("&");
-                }
-            }
-        }
-        return sb.toString();
-    }
-
-}

+ 0 - 24
core/src/main/java/com/tzld/videoVector/util/http/HttpDeleteExpand.java

@@ -1,24 +0,0 @@
-package com.tzld.videoVector.util.http;
-
-import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
-
-import java.net.URI;
-
-public class HttpDeleteExpand extends HttpEntityEnclosingRequestBase {
-    public static final String METHOD_NAME = "DELETE";
-
-    public HttpDeleteExpand() {
-    }
-
-    public HttpDeleteExpand(URI uri) {
-        this.setURI(uri);
-    }
-
-    public HttpDeleteExpand(String uri) {
-        this.setURI(URI.create(uri));
-    }
-
-    public String getMethod() {
-        return "DELETE";
-    }
-}

+ 0 - 97
core/src/main/java/com/tzld/videoVector/util/http/HttpResponseContent.java

@@ -1,97 +0,0 @@
-package com.tzld.videoVector.util.http;
-
-import org.apache.http.Header;
-
-import java.io.UnsupportedEncodingException;
-
-/**
- * HTTP请求响应报文封装类
- */
-public class HttpResponseContent {
-
-    private int statusCode; // 响应状态码
-    private String mimeType; // mime类型
-    private String charsetName; // 字符集
-    private byte[] contentBytes; // 响应报文主体内容的二进制数据
-    private Header[] headers; // 响应头
-
-    /**
-     * 获取响应报文主体内容,字符串,使用响应报文中的字符集编码
-     *
-     * @return
-     */
-    public String getBodyContent() {
-        return this.getBodyContent(charsetName);
-    }
-
-    /**
-     * 获取响应报文主体内容,字符串
-     *
-     * @param charsetName 指定的字符编码
-     * @return
-     */
-    public String getBodyContent(String charsetName) {
-        String str = null;
-        if (charsetName == null) {
-            charsetName = "UTF-8";
-        }
-        try {
-            str = new String(contentBytes, charsetName);
-        } catch (UnsupportedEncodingException e) {
-            // 忽略异常
-            e.printStackTrace();
-        }
-        return str;
-    }
-
-    public boolean isSuccessful() {
-        return statusCode == 200;
-    }
-
-    public int getStatusCode() {
-        return statusCode;
-    }
-
-    public void setStatusCode(int statusCode) {
-        this.statusCode = statusCode;
-    }
-
-    public String getMimeType() {
-        return mimeType;
-    }
-
-    public void setMimeType(String mimeType) {
-        this.mimeType = mimeType;
-    }
-
-    public String getCharsetName() {
-        return charsetName;
-    }
-
-    public void setCharsetName(String charsetName) {
-        this.charsetName = charsetName;
-    }
-
-    public byte[] getContentBytes() {
-        return contentBytes;
-    }
-
-    public void setContentBytes(byte[] contentBytes) {
-        this.contentBytes = contentBytes;
-    }
-
-    public Header[] getHeaders() {
-        return headers;
-    }
-
-    public void setHeaders(Header[] headers) {
-        this.headers = headers;
-    }
-
-    @Override
-    public String toString() {
-        return "HttpResponseContent [statusCode=" + statusCode + ", mimeType=" + mimeType + ", charsetName=" + charsetName
-                + ", bodyContent=" + getBodyContent() + "]";
-    }
-
-}