解決Java處理HTTP請求超時(shí)的問題
在發(fā)送POST或GET請求時(shí),返回超時(shí)異常處理辦法:
捕獲 SocketTimeoutException | ConnectTimeoutException | ConnectionPoolTimeout 異常
三種異常說明:
SocketTimeoutException
:是Java包下拋出的異常,這定義了Socket讀數(shù)據(jù)的超時(shí)時(shí)間,即從server獲取響應(yīng)數(shù)據(jù)須要等待的時(shí)間;當(dāng)讀取或者接收Socket超時(shí)會(huì)拋出SocketTimeoutException。
ConnectTimeoutException
:是Apache的HttpClient包拋出的超時(shí)異常,定義了通過網(wǎng)絡(luò)與server建立連接的超時(shí)時(shí)間,Httpclient包中通過一個(gè)異步線程去創(chuàng)建與server的socket連接,這就是該socket連接的超時(shí)時(shí);
當(dāng)連接HTTPserver或者等待HttpConnectionManager管理的一個(gè)有效連接超時(shí)出錯(cuò)會(huì)拋出ConnectionTimeoutException。
ConnectionPoolTimeout
:也是Apache的HttpClient包拋出的超時(shí)異常,定義了從 ConnectionManager 管理的連接池中取出連接的超時(shí)時(shí)間;出錯(cuò)會(huì)拋出 ConnectionPoolTimeoutException。
總結(jié):
SocketTimeoutException異常是一個(gè)通用的異常,無論是用原生的HTTP請求,還是用Apache下的HttpClient包,在拋出的異常中都需要捕獲 SocketTimeoutException 異常。
例:
public static String doGet(String url, Object params, String contentType) { try { return HttpUtils.doGetSend(url, params, contentType); } catch (SocketTimeoutException | ConnectTimeoutException e) { e.printStackTrace(); System.out.println("請求連接超時(shí):" + e.getMessage()); } catch (IOException e) { e.printStackTrace(); System.out.println("請求異常,異常信息:" + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } return null; }
補(bǔ)充:java 發(fā)送http請求(連接超時(shí)處理)
業(yè)務(wù)背景:
某項(xiàng)目跟第三方公司對接。
業(yè)務(wù)描述:
出于數(shù)據(jù)安全考慮,需要從服務(wù)器發(fā)送請求,來調(diào)用第三方公司提供的接口。但是該場景是銷售類型,響應(yīng)時(shí)間必須夠快,那么就要設(shè)置響應(yīng)的超時(shí)處理。
不然讓客戶看著圈圈在那里轉(zhuǎn)半天,誰買?
項(xiàng)目架構(gòu):
jdk1.7
spring4.2.9
詳細(xì)內(nèi)容:
CloseableHttpClient httpclient = HttpClients.createDefault(); try { HttpPost httpPost = new HttpPost(要訪問的URL); //配置超時(shí) RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); //設(shè)置post請求參數(shù) List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("attr1", 參數(shù)值1)); nvps.add(new BasicNameValuePair("attr2", 參數(shù)值2)); nvps.add(new BasicNameValuePair("attr3", 參數(shù)值3)); …… httpPost.setEntity(new UrlEncodedFormEntity(nvps)); //執(zhí)行post請求 CloseableHttpResponse response = httpclient.execute(httpPost); // 判斷網(wǎng)絡(luò)連接狀態(tài)碼是否正常(0--200都數(shù)正常) if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //獲取響應(yīng)實(shí)體 responseMessage = EntityUtils.toString(response.getEntity(),"utf-8"); System.out.println(responseMessage); if(responseMessage!=null && !"".equals(responseMessage)){ String data = new String(AESUtil.decrypt(Base64.decode(responseMessage), key),"UTF-8"); String msg = translate_PRE(data,trans_type,transNo); result.put("msg", msg); } }else{ System.out.println("請求未成功響應(yīng): "+ response.getStatusLine()); } } catch (ConnectTimeoutException e) { System.out.println(api_type+"請求超時(shí)"); } catch (ClientProtocolException e) { System.out.println("請求失敗"); } catch (Exception e) { e.printStackTrace(); } finally { //釋放連接 try { if(httpclient!=null){ httpclient.close(); } } catch (IOException e) { System.out.println(api_type+"連接無法關(guān)閉"); } } .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); //設(shè)置post請求參數(shù) List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("attr1", 參數(shù)值1)); nvps.add(new BasicNameValuePair("attr2", 參數(shù)值2)); nvps.add(new BasicNameValuePair("attr3", 參數(shù)值3)); …… httpPost.setEntity(new UrlEncodedFormEntity(nvps)); //執(zhí)行post請求 CloseableHttpResponse response = httpclient.execute(httpPost); // 判斷網(wǎng)絡(luò)連接狀態(tài)碼是否正常(0--200都數(shù)正常) if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ //獲取響應(yīng)實(shí)體 responseMessage = EntityUtils.toString(response.getEntity(),"utf-8"); System.out.println(responseMessage); if(responseMessage!=null && !"".equals(responseMessage)){ String data = new String(AESUtil.decrypt(Base64.decode(responseMessage), key),"UTF-8"); String msg = translate_PRE(data,trans_type,transNo); result.put("msg", msg); } }else{ System.out.println("請求未成功響應(yīng): "+ response.getStatusLine()); } } catch (ConnectTimeoutException e) { System.out.println(api_type+"請求超時(shí)"); } catch (ClientProtocolException e) { System.out.println("請求失敗"); } catch (Exception e) { e.printStackTrace(); } finally { //釋放連接 try { if(httpclient!=null){ httpclient.close(); } } catch (IOException e) { System.out.println(api_type+"連接無法關(guān)閉"); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
Java數(shù)據(jù)結(jié)構(gòu)之List的使用總結(jié)
List是Java中比較常用的集合類,指一系列存儲(chǔ)數(shù)據(jù)的接口和類,可以解決復(fù)雜的數(shù)據(jù)存儲(chǔ)問題,本文就來拿實(shí)際案例總結(jié)介紹一下List的使用方法,感興趣的朋友快來看看吧2021-11-11mybatis?獲取更新(update)記錄的id之<selectKey>用法說明
這篇文章主要介紹了mybatis?獲取更新(update)記錄的id之<selectKey>用法說明,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05java URL 獲取PHP JSON 數(shù)據(jù)
這篇文章主要介紹了java URL 獲取PHP JSON 數(shù)據(jù),需要的朋友可以參考下2016-04-04Mybatis批量插入更新xml方式和注解方式的方法實(shí)例
這篇文章主要給大家介紹了關(guān)于Mybatis批量插入更新xml方式和注解方式的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Mybatis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12springBoot項(xiàng)目打包idea的多種方法
這篇文章主要介紹了springBoot項(xiàng)目打包idea的多種方法,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07java實(shí)現(xiàn)抖音飛機(jī)大作戰(zhàn)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)抖音飛機(jī)大作戰(zhàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04