Browse Source

调用二厂接口设置超时时间

xiaosonghong 1 week ago
parent
commit
8ab736c187
1 changed files with 11 additions and 0 deletions
  1. 11 0
      src/main/java/com/steerinfo/dil/util/HTTPRequestUtils.java

+ 11 - 0
src/main/java/com/steerinfo/dil/util/HTTPRequestUtils.java

@@ -3,6 +3,7 @@ package com.steerinfo.dil.util;
 import com.alibaba.fastjson.JSONObject;
 import org.apache.http.HttpEntity;
 import org.apache.http.ParseException;
+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.client.methods.HttpPost;
@@ -41,6 +42,10 @@ public class HTTPRequestUtils {
         s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
         //设置参数到请求对象中
         httpPost.setEntity(s);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout(10 * 1000)
+                .setSocketTimeout(10 * 1000)
+                .build();
 
         System.out.println("请求地址:" + url);
         System.out.println(json);
@@ -51,6 +56,7 @@ public class HTTPRequestUtils {
 //        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
         httpPost.setHeader("Content-type", "application/json");
         httpPost.setHeader("-UserAgent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
+        httpPost.setConfig(requestConfig);
 
         //执行请求操作,并拿到结果(同步阻塞)
         CloseableHttpResponse response = client.execute(httpPost);
@@ -136,6 +142,10 @@ public class HTTPRequestUtils {
         CloseableHttpClient client = HttpClients.createDefault();
         //创建post方式请求对象
         HttpGet httpGet = new HttpGet(url);
+        RequestConfig requestConfig = RequestConfig.custom()
+                .setConnectTimeout(10 * 1000)
+                .setSocketTimeout(10 * 1000)
+                .build();
         //装填参数
         //StringEntity s = new StringEntity(json.toString(), "utf-8");
         //s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
@@ -149,6 +159,7 @@ public class HTTPRequestUtils {
 //        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
         httpGet.setHeader("Content-type", "application/json");
         httpGet.setHeader("-UserAgent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
+        httpGet.setConfig(requestConfig);
 
         //执行请求操作,并拿到结果(同步阻塞)
         CloseableHttpResponse response = client.execute(httpGet);