解決Java處理HTTP請(qǐng)求超時(shí)的問題
捕獲 SocketTimeoutException | ConnectTimeoutException | ConnectionPoolTimeout 異常
三種異常說(shuō)明:
SocketTimeoutException:是Java包下拋出的異常,這定義了Socket讀數(shù)據(jù)的超時(shí)時(shí)間,即從server獲取響應(yīng)數(shù)據(jù)須要等待的時(shí)間;當(dāng)讀取或者接收Socket超時(shí)會(huì)拋出SocketTimeoutException。
ConnectTimeoutException:是Apache的HttpClient包拋出的超時(shí)異常,定義了通過(guò)網(wǎng)絡(luò)與server建立連接的超時(shí)時(shí)間,Httpclient包中通過(guò)一個(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è)通用的異常,無(wú)論是用原生的HTTP請(qǐng)求,還是用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('請(qǐng)求連接超時(shí):' + e.getMessage()); } catch (IOException e) { e.printStackTrace(); System.out.println('請(qǐng)求異常,異常信息:' + e.getMessage()); } catch (Exception e) { e.printStackTrace(); } return null;}
補(bǔ)充:java 發(fā)送http請(qǐng)求(連接超時(shí)處理)
業(yè)務(wù)背景:某項(xiàng)目跟第三方公司對(duì)接。
業(yè)務(wù)描述:出于數(shù)據(jù)安全考慮,需要從服務(wù)器發(fā)送請(qǐng)求,來(lái)調(diào)用第三方公司提供的接口。但是該場(chǎng)景是銷售類型,響應(yīng)時(shí)間必須夠快,那么就要設(shè)置響應(yīng)的超時(shí)處理。
不然讓客戶看著圈圈在那里轉(zhuǎn)半天,誰(shuí)買?
項(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請(qǐng)求參數(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請(qǐng)求 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('請(qǐng)求未成功響應(yīng): '+ response.getStatusLine()); } } catch (ConnectTimeoutException e) { System.out.println(api_type+'請(qǐng)求超時(shí)'); } catch (ClientProtocolException e) { System.out.println('請(qǐng)求失敗'); } catch (Exception e) { e.printStackTrace(); } finally { //釋放連接 try { if(httpclient!=null){ httpclient.close(); } } catch (IOException e) { System.out.println(api_type+'連接無(wú)法關(guān)閉'); } } .setConnectTimeout(5000).setConnectionRequestTimeout(5000) .setSocketTimeout(5000).build(); httpPost.setConfig(requestConfig); //設(shè)置post請(qǐng)求參數(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請(qǐng)求 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('請(qǐng)求未成功響應(yīng): '+ response.getStatusLine()); } } catch (ConnectTimeoutException e) { System.out.println(api_type+'請(qǐng)求超時(shí)'); } catch (ClientProtocolException e) { System.out.println('請(qǐng)求失敗'); } catch (Exception e) { e.printStackTrace(); } finally { //釋放連接 try { if(httpclient!=null){ httpclient.close(); } } catch (IOException e) { System.out.println(api_type+'連接無(wú)法關(guān)閉'); } }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. phpstudy apache開啟ssi使用詳解2. .Net Core和RabbitMQ限制循環(huán)消費(fèi)的方法3. JSP之表單提交get和post的區(qū)別詳解及實(shí)例4. Xml簡(jiǎn)介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理5. 詳解瀏覽器的緩存機(jī)制6. jsp文件下載功能實(shí)現(xiàn)代碼7. 如何在jsp界面中插入圖片8. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享9. jsp實(shí)現(xiàn)登錄驗(yàn)證的過(guò)濾器10. .Net加密神器Eazfuscator.NET?2023.2?最新版使用教程
