解決Java處理HTTP請求超時的問題
捕獲 SocketTimeoutException | ConnectTimeoutException | ConnectionPoolTimeout 異常
三種異常說明:
SocketTimeoutException:是Java包下拋出的異常,這定義了Socket讀數(shù)據(jù)的超時時間,即從server獲取響應(yīng)數(shù)據(jù)須要等待的時間;當(dāng)讀取或者接收Socket超時會拋出SocketTimeoutException。
ConnectTimeoutException:是Apache的HttpClient包拋出的超時異常,定義了通過網(wǎng)絡(luò)與server建立連接的超時時間,Httpclient包中通過一個異步線程去創(chuàng)建與server的socket連接,這就是該socket連接的超時時;
當(dāng)連接HTTPserver或者等待HttpConnectionManager管理的一個有效連接超時出錯會拋出ConnectionTimeoutException。
ConnectionPoolTimeout:也是Apache的HttpClient包拋出的超時異常,定義了從 ConnectionManager 管理的連接池中取出連接的超時時間;出錯會拋出 ConnectionPoolTimeoutException。
總結(jié):SocketTimeoutException異常是一個通用的異常,無論是用原生的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('請求連接超時:' + e.getMessage()); } catch (IOException e) { e.printStackTrace(); System.out.println('請求異常,異常信息:' + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } return null;}
補(bǔ)充:java 發(fā)送http請求(連接超時處理)
業(yè)務(wù)背景:某項(xiàng)目跟第三方公司對接。
業(yè)務(wù)描述:出于數(shù)據(jù)安全考慮,需要從服務(wù)器發(fā)送請求,來調(diào)用第三方公司提供的接口。但是該場景是銷售類型,響應(yīng)時間必須夠快,那么就要設(shè)置響應(yīng)的超時處理。
不然讓客戶看著圈圈在那里轉(zhuǎn)半天,誰買?
項(xiàng)目架構(gòu):jdk1.7
spring4.2.9
詳細(xì)內(nèi)容:CloseableHttpClient httpclient = HttpClients.createDefault();try { HttpPost httpPost = new HttpPost(要訪問的URL); //配置超時 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+'請求超時'); } 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+'請求超時'); } 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)閉'); } }
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. IntelliJ IDEA設(shè)置背景圖片的方法步驟2. 增大python字體的方法步驟3. JAMon(Java Application Monitor)備忘記4. Python OpenCV去除字母后面的雜線操作5. Python TestSuite生成測試報(bào)告過程解析6. docker /var/lib/docker/aufs/mnt 目錄清理方法7. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)8. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法9. Python os庫常用操作代碼匯總10. Java類加載機(jī)制實(shí)現(xiàn)步驟解析
