Explorar el Código

增加httpTemplete模板类的Post方法及示例

zhuoning hace 3 años
padre
commit
d0feab406a

+ 10 - 0
huimv-hy-production/huimv.hy.autoGetData/pom.xml

@@ -23,6 +23,16 @@
             <artifactId>fastjson</artifactId>
             <version>1.2.28</version>
         </dependency>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-test</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <version>4.12-beta-3</version>
+        </dependency>
     </dependencies>
 
 </project>

+ 16 - 11
huimv-hy-production/huimv.hy.autoGetData/src/main/java/com/huimv/production/autoGetData/service/impl/AutoGetErpDataImpl.java

@@ -11,7 +11,7 @@ import com.huimv.production.autoGetData.entity.ProductionGroup;
 import com.huimv.production.autoGetData.repo.IndexParameterRepository;
 import com.huimv.production.autoGetData.repo.ProductionGroupRepo;
 import com.huimv.production.autoGetData.service.IAutoGetErpData;
-import com.huimv.production.autoGetData.utils.HttpClientUtil;
+import com.huimv.production.autoGetData.utils.HttpTemplete;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
@@ -45,7 +45,7 @@ public class AutoGetErpDataImpl implements IAutoGetErpData {
     @Value("${erp.datasource.serviceName}")
     private String serviceName;
     @Autowired
-    private HttpClientUtil httpClientUtil;
+    private HttpTemplete httpClientUtil;
     @Autowired
     private RestTemplate template;
     @Autowired
@@ -423,14 +423,14 @@ public class AutoGetErpDataImpl implements IAutoGetErpData {
         timeoutMap.put("requestTimeout", 120000);
         timeoutMap.put("socketTimeout", 120000);
         String url = apiIp + apiPort + serviceName +"/getManyFarmProduce";
-        System.out.println("url="+url);
-        System.out.println("paramsMap="+paramsMap.toString());
-        System.out.println("timeoutMap="+timeoutMap.toString());
-        System.out.println("开始取数="+new Date(System.currentTimeMillis()));
+        log.info("多个牧场生产数据访问地址="+url);
+        log.info("业务请求参数="+paramsMap.toString());
+        log.info("超时参数="+timeoutMap.toString());
+        log.info("开始取数="+new Date(System.currentTimeMillis()));
         //
         JSONObject outJo = httpClientUtil.get(url,paramsMap,timeoutMap);
-        System.out.println("返回结果="+outJo);
-        System.out.println("完成取数="+new Date(System.currentTimeMillis()));
+        log.info("返回结果="+outJo);
+        log.info("完成取数="+new Date(System.currentTimeMillis()));
         if(outJo.getBoolean("status")){
             JSONObject contentJo = outJo.getJSONObject("content");
             if(contentJo.getBoolean("success")){
@@ -491,8 +491,10 @@ public class AutoGetErpDataImpl implements IAutoGetErpData {
         timeoutMap.put("requestTimeout", 120000);
         timeoutMap.put("socketTimeout", 120000);
         String url = apiIp + apiPort + serviceName +"/getManyFarmStock";
-        log.info("获取多个牧场的存栏="+url);
-        log.info("开始取数="+new Date(System.currentTimeMillis()));
+        log.info("获取多个牧场的存栏数据请求地址="+url);
+        log.info("业务请求参数="+paramsMap.toString());
+        log.info("超时参数="+timeoutMap.toString());
+        log.info("开始取数="+new Date(System.currentTimeMillis()));
         //
         JSONObject outJo = httpClientUtil.get(url,paramsMap,timeoutMap);
         log.info("返回结果="+outJo);
@@ -522,12 +524,15 @@ public class AutoGetErpDataImpl implements IAutoGetErpData {
         paramsMap.put("accessToken", token);
         paramsMap.put("year", dateUtil.getThisYear());
         paramsMap.put("month", dateUtil.getThisMonth());
+        System.out.println("paramsMap>>"+paramsMap);
         Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
         timeoutMap.put("connectTimeout", 120000);
         timeoutMap.put("requestTimeout", 120000);
         timeoutMap.put("socketTimeout", 120000);
         String url = apiIp + apiPort + serviceName +"/getCostWithManyFarm";
-        log.info("获取多个牧场的成本="+url);
+        log.info("获取多个牧场的成本数据访问地址="+url);
+        log.info("业务请求参数="+paramsMap.toString());
+        log.info("超时参数="+timeoutMap.toString());
         log.info("开始取数="+new Date(System.currentTimeMillis()));
         //
         JSONObject outJo = httpClientUtil.get(url,paramsMap,timeoutMap);

+ 107 - 70
huimv-hy-production/huimv.hy.autoGetData/src/main/java/com/huimv/production/autoGetData/utils/HttpClientUtil.java

@@ -3,21 +3,19 @@ package com.huimv.production.autoGetData.utils;
 import com.alibaba.fastjson.JSONObject;
 import org.apache.http.*;
 import org.apache.http.client.ClientProtocolException;
-import org.apache.http.client.HttpClient;
 import org.apache.http.client.config.RequestConfig;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.*;
-import org.apache.http.conn.routing.HttpRoute;
+import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.CloseableHttpClient;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.client.HttpClientBuilder;
 import org.apache.http.impl.client.HttpClients;
-import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
 import org.apache.http.message.BasicNameValuePair;
 import org.apache.http.util.EntityUtils;
 import org.springframework.stereotype.Component;
 
 import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.Charset;
 import java.util.*;
 
 /**
@@ -29,40 +27,64 @@ import java.util.*;
  * @Create : 2020-12-25
  **/
 @Component
-public class HttpClientUtil {
-    String httpIp = "http://121.40.221.149:9100";
+public class HttpTemplete {
+    private String testHttpIp = "http://localhost:9105";
 
-    public static void main(String[] args) throws Exception {
-        //
-        HttpClientUtil client = new HttpClientUtil();
-//        client.testGetRequest1();
-        client.testGetRequest2();
-    }
+//    public static void main(String[] args) throws Exception {
+//        //
+//        HttpTemplete client = new HttpTemplete();
+////        client.testGetRequest1();
+//        client.testGetRequest2();
+//    }
 
-    private void testGetRequest1() throws IOException {
-        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
-        timeoutMap.put("connectTimeout", 5000);
-        timeoutMap.put("requestTimeout", 5000);
-        timeoutMap.put("socketTimeout", 5000);
-        String url = httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
-        // test error
-        url = httpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c&userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
+    public JSONObject post(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
+        // 创建默认的httpClient实例.
         CloseableHttpClient httpClient = getHttpClientConnection();
-        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, timeoutMap));
-        // 打印响应状态
-        System.out.println("响应状态1 =" + response.getStatusLine());
+        //
+        int connectTimeout = timeoutMap.get("connectTimeout");
+        int requestTimeout = timeoutMap.get("requestTimeout");
+        int socketTimeout = timeoutMap.get("socketTimeout");
+        // 创建httpPost
+        HttpPost httpPost = new HttpPost(url);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setSocketTimeout(socketTimeout) //服务器响应超时时间
+                .setConnectTimeout(connectTimeout) //连接服务器超时时间
+                .setConnectionRequestTimeout(requestTimeout)
+                .build();
+        httpPost.setConfig(requestConfig);
+        // 创建参数队列
+        List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
+        Set<Map.Entry<String, String>> entrySet = paramsMap.entrySet();
+        for (Map.Entry<String, String> e : entrySet) {
+            String name = e.getKey();
+            String value = e.getValue();
+            NameValuePair pair = new BasicNameValuePair(name, value);
+            paramsList.add(pair);
+        }
+        UrlEncodedFormEntity content = new UrlEncodedFormEntity(paramsList, "UTF-8");
+        //处理乱码
+//        StringEntity content = new StringEntity(paramsList.toString(), Charset.forName("UTF-8"));// 第二个参数,设置后才会对,内容进行编码
+//        content.setContentType("application/soap+xml; charset=UTF-8");
+//        content.setContentEncoding("UTF-8");
+        httpPost.setEntity(content);
+//        HttpUriRequest httpPost = RequestBuilder.post().setUri(url).setEntity(content).setConfig(requestConfig);
+        CloseableHttpResponse response = httpClient.execute(httpPost);
+        // 获取响应实体
+        HttpEntity entity = response.getEntity();
         try {
             if (response.getStatusLine().getStatusCode() == 200) {
-                // 获取响应实体
-                HttpEntity entity = response.getEntity();
                 // 打印响应内容
                 String text = EntityUtils.toString(entity, "utf-8");
-                System.out.println("响应内容=" + text);
-
-                JSONObject resultJo = JSONObject.parseObject(text);
-                System.out.println("accessToken="+resultJo.getString("accessToken"));
-            } else {
-                System.out.println("请求失败");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", true);
+                resultJo.put("content", text);
+                return resultJo;
+            }else{
+                String text = EntityUtils.toString(entity, "utf-8");
+                JSONObject resultJo = new JSONObject();
+                resultJo.put("status", false);
+                resultJo.put("content", text);
+                return resultJo;
             }
         } finally {
             response.close();
@@ -70,76 +92,90 @@ public class HttpClientUtil {
         }
     }
 
-    private void testGetRequest2() throws IOException {
-        Map<String, String> paramsMap = new HashMap<String, String>();
-        paramsMap.put("userId", "20210501");
-        paramsMap.put("timestamp", "45546546454");
-        paramsMap.put("random", "1156");
-        paramsMap.put("sign", "7fa431325504e01e9fa87ed0e274c40c");
-
-        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
-        timeoutMap.put("connectTimeout", 5000);
-        timeoutMap.put("requestTimeout", 5000);
-        timeoutMap.put("socketTimeout", 5000);
-
-        String url = httpIp + "/token/getToken";
-        //        get(url, paramsMap, timeoutMap);
-        //
-        JSONObject resultJo = get(url,paramsMap,timeoutMap);
-        System.out.println("status="+resultJo.getBoolean("status"));
-        System.out.println("content="+resultJo.getJSONObject("content"));
-    }
 
     /**
-     * @Method      : get
-     * @Description : 
-     * @Params      : [url, paramsMap, timeoutMap]
-     * @Return      : com.alibaba.fastjson.JSONObject
-     * 
-     * @Author      : ZhuoNing
-     * @Date        : 2021/11/18       
-     * @Time        : 17:39
+     * @Method : get
+     * @Description :
+     * @Params : [url, paramsMap, timeoutMap]
+     * @Return : com.alibaba.fastjson.JSONObject
+     * @Author : ZhuoNing
+     * @Date : 2021/11/18
+     * @Time : 17:39
      */
     public JSONObject get(String url, Map<String, String> paramsMap, Map<String, Integer> timeoutMap) throws IOException {
-        if(timeoutMap == null){
+        if (timeoutMap == null) {
             timeoutMap.put("connectTimeout", 5000);
             timeoutMap.put("requestTimeout", 5000);
             timeoutMap.put("socketTimeout", 5000);
         }
         //
         CloseableHttpClient httpClient = getHttpClientConnection();
-        //
+        //执行//获取请求内容
         CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, paramsMap, timeoutMap));
         try {
+            // 获取响应实体
+            HttpEntity entity = response.getEntity();
             // 打印响应状态
             if (response.getStatusLine().getStatusCode() == 200) {
-                // 获取响应实体
-                HttpEntity entity = response.getEntity();
                 // 打印响应内容
                 String text = EntityUtils.toString(entity, "utf-8");
                 JSONObject resultJo = new JSONObject();
-                resultJo.put("status",true);
-                resultJo.put("content",text);
+                resultJo.put("status", true);
+                resultJo.put("content", text);
                 return resultJo;
             } else {
+                String text = EntityUtils.toString(entity, "utf-8");
                 JSONObject resultJo = new JSONObject();
-                resultJo.put("status",false);
-                resultJo.put("content","请求失败");
+                resultJo.put("status", false);
+                resultJo.put("content", text);
                 return resultJo;
             }
         } finally {
             response.close();
             httpClient.close();
         }
+    }
+
+    private void testGetRequest1() throws IOException {
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", 5000);
+        timeoutMap.put("requestTimeout", 5000);
+        timeoutMap.put("socketTimeout", 5000);
+        String url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
+        // test error
+        url = testHttpIp + "/token/getToken?userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c&userId=20210501&timestamp=45546546454&random=1156&sign=7fa431325504e01e9fa87ed0e274c40c";
+        CloseableHttpClient httpClient = getHttpClientConnection();
+        CloseableHttpResponse response = httpClient.execute(getHttpRequest(url, timeoutMap));
+        // 打印响应状态
+        System.out.println("响应状态1 =" + response.getStatusLine());
+        try {
+            if (response.getStatusLine().getStatusCode() == 200) {
+                // 获取响应实体
+                HttpEntity entity = response.getEntity();
+                // 打印响应内容
+                String text = EntityUtils.toString(entity, "utf-8");
+                System.out.println("响应内容=" + text);
 
+                JSONObject resultJo = JSONObject.parseObject(text);
+                System.out.println("accessToken=" + resultJo.getString("accessToken"));
+            } else {
+                System.out.println("请求失败");
+            }
+        } finally {
+            response.close();
+            httpClient.close();
+        }
     }
 
+    //
     private CloseableHttpClient getHttpClientConnection() {
+        //创建默认实例
         CloseableHttpClient httpclient = HttpClients.createDefault();
+        //
 //        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
         return httpclient;
     }
-
+    //
     private HttpUriRequest getHttpRequest(String url, Map<String, String> map, Map<String, Integer> timeoutMap) {
         int connectTimeout = timeoutMap.get("connectTimeout");
         int requestTimeout = timeoutMap.get("requestTimeout");
@@ -153,6 +189,7 @@ public class HttpClientUtil {
             NameValuePair pair = new BasicNameValuePair(name, value);
             params.add(pair);
         }
+        //
         RequestConfig requestConfig = RequestConfig.custom()
                 .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(requestTimeout)
                 .setSocketTimeout(socketTimeout).build();
@@ -161,7 +198,7 @@ public class HttpClientUtil {
                 .setConfig(requestConfig).build();
         return httpGet;
     }
-
+    //
     private HttpGet getHttpRequest(String url, Map<String, Integer> timeoutMap) {
         int connectTimeout = timeoutMap.get("connectTimeout");
         int requestTimeout = timeoutMap.get("requestTimeout");
@@ -177,7 +214,7 @@ public class HttpClientUtil {
     }
 
     //test
-    public void get() {
+    private void get() {
 //        CloseableHttpClient httpclient = HttpClients.createDefault();
 //        try {
 //            // 创建httpget.

+ 73 - 0
huimv-hy-production/huimv.hy.autoGetData/src/test/java/com/huimv/production/autoGetData/utils/HttpTempleteTest.java

@@ -0,0 +1,73 @@
+package com.huimv.production.autoGetData.utils;
+
+import com.alibaba.fastjson.JSONObject;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Project : huimv.shiwan
+ * @Package : com.huimv.biosafety.uface.controller
+ * @Description : TODO
+ * @Version : 1.0
+ * @Author : ZhuoNing
+ * @Create : 2020-12-25
+ **/
+@SpringBootTest
+public class HttpTempleteTest {
+    @Autowired
+    private HttpTemplete httpTemplete;
+    //本地测试地址
+    String testLocalHttpIp = "http://localhost:9100";
+    //远程测试地址
+    String testRemoteHttpIp = "http://121.40.221.149:9100";
+
+    //### 推送接口使用说明 ###
+    //1.服务端先要提供接收端口(ip地址+接口访问路径)
+    //2.用httpTemplete模板类用Post或Get方式进行数据推送
+
+    //用Post方法推送接口数据--示例
+    @Test
+    public void testPost() throws IOException {
+        String url = testLocalHttpIp + "/demo/saveDemo";
+        System.out.println("测试推送地址:"+url);
+
+        Map<String,String> paramsMap = new HashMap<String,String>();
+        paramsMap.put("name", "tony");
+        paramsMap.put("age", "25");
+        paramsMap.put("no", "1156");
+
+        Map<String,Integer> timeoutMap = new HashMap<String,Integer>();
+        timeoutMap.put("connectTimeout", 5000);
+        timeoutMap.put("requestTimeout", 5000);
+        timeoutMap.put("socketTimeout", 5000);
+        // 用Post方法推送接口数据
+        JSONObject outJo = httpTemplete.post(url,paramsMap,timeoutMap);
+        System.out.println("测试结果="+outJo);
+    }
+
+    //用Get方法推送接口数据--示例
+    @Test
+    public void testGet() throws IOException {
+        Map<String, String> paramsMap = new HashMap<String, String>();
+        paramsMap.put("userId", "20210501");
+        paramsMap.put("timestamp", "45546546454");
+        paramsMap.put("random", "1156");
+        paramsMap.put("sign", "7fa431325504e01e9fa87ed0e274c40c");
+
+        Map<String, Integer> timeoutMap = new HashMap<String, Integer>();
+        timeoutMap.put("connectTimeout", 5000);
+        timeoutMap.put("requestTimeout", 5000);
+        timeoutMap.put("socketTimeout", 5000);
+
+        String url = testRemoteHttpIp + "/token/getToken";
+        //用Get方法推送接口数据
+        JSONObject resultJo = httpTemplete.get(url, paramsMap, timeoutMap);
+        System.out.println("status=" + resultJo.getBoolean("status"));
+        System.out.println("content=" + resultJo.getJSONObject("content"));
+    }
+}