Browse Source

httpclient 是为了微信小程序端的下发提醒使用

cr7118@sina.cn 3 years ago
parent
commit
f616cdf6f7

+ 59 - 0
application-task/src/main/java/com/jihengbel/intelligent/applicationtask/common/HttpCilentUntil.java

@@ -0,0 +1,59 @@
+package com.jihengbel.intelligent.applicationtask.common;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.client.config.RequestConfig;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.util.EntityUtils;
+
+import java.net.URLEncoder;
+import java.util.Map;
+
+public class HttpCilentUntil {
+
+    /**
+     * 微信请求返回结果
+     * @param url
+     * @param params
+     * @return
+     */
+    public static String httpRequestToString(String url, Map<String, String> params) {
+        String result = null;
+        CloseableHttpClient hp=null;
+        try {
+            String parameters = "";
+            boolean hasParams = false;
+            for (String key : params.keySet()) {
+                String value = URLEncoder.encode(params.get(key), "UTF-8");
+                parameters += key + "=" + value + "&";
+                hasParams = true;
+            }
+            if (hasParams) {
+                parameters = parameters.substring(0, parameters.length() - 1);
+            }
+            if(parameters.length()>0){
+                url += "?" + parameters;
+            }
+            hp = HttpClients.createDefault();
+            RequestConfig requestConfig = RequestConfig.custom()
+                    .setConnectTimeout(5000).setConnectionRequestTimeout(1000)
+                    .setSocketTimeout(5000).build();
+            HttpGet hg = new HttpGet( url);
+            hg.setHeader("Content-Type", "application/x-www-form-urlencoded");
+            hg.setHeader("Accept-Charset", "UTF-8");
+            hg.setHeader("contentType", "utf-8");
+            hg.setConfig(requestConfig);
+            CloseableHttpResponse response=hp.execute(hg);
+            HttpEntity entity = response.getEntity();
+            result = EntityUtils.toString(entity, "utf-8");
+
+        } catch (Throwable e) {
+            e.printStackTrace();
+            return null;
+        }
+        return result;
+    }
+
+}