Переглянути джерело

webapi http 请求协议缓存版

andy 1 рік тому
батько
коміт
1396fd0644
1 змінених файлів з 123 додано та 0 видалено
  1. 123 0
      src/main/java/com/scbfkj/uni/process/Http.java

+ 123 - 0
src/main/java/com/scbfkj/uni/process/Http.java

@@ -0,0 +1,123 @@
+package com.scbfkj.uni.process;
+
+import com.scbfkj.uni.library.DataFormatUtil;
+import com.scbfkj.uni.library.UniReturnUtil;
+import com.scbfkj.uni.system.Config;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.*;
+import org.apache.http.entity.ByteArrayEntity;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.util.EntityUtils;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+
+public class Http {
+
+    private static final DataBase DATA_BASE = new DataBase();
+
+    private final static PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
+    private static HttpClient httpClient;
+
+    static {
+
+        cm.setMaxTotal(100); // 设置最大连接数
+        cm.setDefaultMaxPerRoute(20); // 设置每个路由的最大连接数
+        httpClient = HttpClients.custom()
+                .setConnectionManager(cm)
+                .build();
+
+    }
+
+
+    public Map<String, Object> execWebApiByDataSourceId(String dataSourceId, Object headers, String method, Object defaultBody) throws Exception {
+        Map<String, Object> config = queryConnectionStr(dataSourceId);
+
+        String host;
+        if (Objects.isNull(headers)) {
+            headers = DataFormatUtil.toMap(config.get("headers"));
+        }
+        if (Objects.isNull(method)) {
+            method = "post";
+        }
+        if (Objects.isNull(defaultBody)) {
+            defaultBody = config.get("body");
+        }
+        host = config.get("host").toString();
+        return execWebApi(headers, method, defaultBody, host);
+    }
+
+    public Map<String, Object> execWebApi(Object headers, String method, Object defaultBody, String url) throws IOException {
+
+        if (Config.isDebug()) {
+            System.out.println("url: " + DataFormatUtil.toString(url));
+            System.out.println("method: " + DataFormatUtil.toString(method));
+            System.out.println("headers: " + DataFormatUtil.toString(headers));
+            System.out.println("body: " + DataFormatUtil.toString(defaultBody));
+        }
+        HttpUriRequest request;
+
+        switch (method.toLowerCase()) {
+            case "get" -> {
+                request = new HttpGet(url);
+            }
+            case "put" -> {
+                request = new HttpPut(url);
+                ((HttpPut) request).setEntity(new ByteArrayEntity(DataFormatUtil.toString(defaultBody).getBytes(StandardCharsets.UTF_8)));
+            }
+            case "delete" -> {
+                request = new HttpDelete(url);
+            }
+            default -> {
+                request = new HttpPost(url);
+                ((HttpPost) request).setEntity(new ByteArrayEntity(DataFormatUtil.toString(defaultBody).getBytes(StandardCharsets.UTF_8)));
+            }
+        }
+
+        if (headers instanceof Map hs) {
+
+            hs.forEach((k, v) -> {
+                request.addHeader((String) k, String.valueOf(v));
+            });
+
+        }
+
+        try {
+            HttpResponse response = httpClient.execute(request);
+            int statusCode = response.getStatusLine().getStatusCode();
+            String responseBody = EntityUtils.toString(response.getEntity());
+            if (statusCode >= 200 && statusCode < 300) {
+                return UniReturnUtil.success(responseBody);
+            } else {
+                return UniReturnUtil.fail(responseBody);
+            }
+        }catch (Exception e){
+            return UniReturnUtil.fail(e);
+        }
+
+    }
+
+
+    private static Map<String, Object> queryConnectionStr(String datasourceId) throws Exception {
+        List<Map<String, Object>> result = DATA_BASE.query(Config.getCenterConnectionStr(), """
+                select host,httpheaders,httpbody
+                from datasource
+                where datasourceid = ?""", datasourceId);
+        if (result.isEmpty()) {
+            throw new RuntimeException("数据源错误:没有找到数据源");
+        }
+        return result.stream().findFirst().map(it -> {
+            HashMap<String, Object> hashMap = new HashMap<>();
+            hashMap.put("url", it.get("host"));
+            hashMap.put("headers", it.get("httpheaders"));
+            hashMap.put("body", it.get("httpbody"));
+            return hashMap;
+        }).get();
+    }
+}