1. 程式人生 > 實用技巧 >java中第三方系統進行post和get通訊超時設定

java中第三方系統進行post和get通訊超時設定

部落格轉載https://blog.csdn.net/shenzhennba/article/details/83051853

1、Java開發我們常常需要和第三方系統進行通訊,通訊的方式有多種,如

(1)dubbo

(2)webservice

(3)微服務

(4)CloseableHttpClient等

2、以CloseableHttpClient為例 設定思路

  首先請求配置物件RequestConfig設定超時時間

  然後設定到 HttpGet 或 HttpPost 請求方法物件

3、以CloseableHttpClient為例

package com.gbm.common.util;

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 org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class HttpUtil { private static Logger logger = LoggerFactory.getLogger(HttpUtil.class); public static String HttpGet(String Url, String token){ String result
=null; CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse newresponse = null; try{ RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(120000) .setSocketTimeout(120000).setConnectTimeout(120000).build(); //設定2分鐘超時 HttpGet httpget = new HttpGet(Url); httpget.setConfig(requestConfig); httpget.setHeader("token-Authorization", token); try{ newresponse = httpclient.execute(httpget); HttpEntity entity = newresponse.getEntity(); result = EntityUtils.toString(entity); }finally{ newresponse.close(); } }catch(Exception e){ logger.error("請求url:" + Url + "異常,異常資訊:" + e.getMessage()); } finally { // 關閉連線,釋放資源 try { httpclient.close(); } catch (IOException e) { logger.error("關閉CloseableHttpClient異常,異常資訊:" + e.getMessage()); } } return result; } }