最近同步數據的時候發現了一個問題,我本身后臺插入數據后給其他部門后臺做同步。說簡單一點其實就是調用對方提供的接口,進行HTTP請求調用。然后后面發現問題了。HTTP請求的話,有可能請求超時,中斷失敗,IO異常其實都有可能,如果是平時打開一個網頁還好,打不開的時候,你會關掉,或者他頁面給你顯示信息。但是同步,不可以這樣做,一旦請求失敗,必須讓數據正確的同步,今天才意識到這個問題的重要性。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
String httpUrl = "https://www.baidu.com/s?ie=UTF-8&tn=90594569_hao_pg&wd=1" ; URL url = null ; HttpURLConnection httpConn = null ; String result = "" ; try { String address = httpUrl; url = new URL(address); httpConn = (HttpURLConnection) url.openConnection(); //A URL connection can be used for input and/or output. Set the //DoInput flag to true if you intend to use the URL connection for input, //false if not. The default is true. //URL連接可用于input或output。如果想用URL連接輸入,設置DoInput標簽為true。 //輸入和輸出是針對計算機的,如果以程序員的角度考慮,經常弄混。 //input輸入,output輸出,那么不是從output里read,input中write嗎,其實相反 //input輸入進計算機,計算機才能讀,所以是從input read,而output是計算機輸出,通過output write。 httpConn.setDoOutput( false ); //所以如果setDoInput(false),想從URLConnection讀取時不能讀取 //Cannot read from URLConnection if doInput=false (call setDoInput(true)) httpConn.setDoInput( true ); //連接建立超時時間還有讀取數據超時時間, httpConn.setConnectTimeout( 600000 ); httpConn.setReadTimeout( 600000 ); httpConn.setRequestMethod( "GET" ); httpConn.connect(); //獲取狀態碼 int code = httpConn.getResponseCode(); System.out.println(code); //讀http請求響應 BufferedReader reader = new BufferedReader( new InputStreamReader(httpConn.getInputStream())); String line; while ((line = reader.readLine()) != null ) { result = result + line+ "\n" ; } System.out.println(result); //關閉IO和連接 reader.close(); httpConn.disconnect(); } catch (Exception e){ log.error(e); } finally { if (httpConn!= null ) httpConn.disconnect(); } |
代碼看上去寫的沒什么,該釋放資源的地方也釋放了。該打日志輸出的也打了。其實問題就是異常的處理。之前以為一些東西沒有同步過去是因為連接超時的問題。所以特地捕獲SocketTimeoutException異常,后面看了日志之后,發現是同步接口那邊服務器的問題,報了502錯誤。其實異常是IO異常。
無論是那種情況,我們都要在出現這種問題之后,再次地把請求發送過去,根據接口返回的結果,確認對方已經同步到。如果服務器暫時性的出了問題,我們可以暫停一小段時間后,然后再次請求。
所以暫時想到的方法是,由于同步的實時性要求不高,那么可以間隔的時間可以長一點。然后循環,另起線程,每次間隔5分鐘,直至結果正常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
catch (Exception e){ for ( int i = 0 ; i < 6 ; i++) { Thread t = new Thread(){ public void run(){get();}}; t.start(); if (result.equals( "ok" )){ break ; } try { Thread.sleep( 300000 ); } catch (InterruptedException e2) { log.error(e2); } } log.error(e); } |
以上就是對Java HttpURLConnection超時和IO異常處理的資料整理,后續繼續補充相關資料,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/iaiti/article/details/52036947