httpUrlConnection如何做到連接超時重復發送請求3次然后判定失敗呢,捕獲了超時例外,在catch中如何處理呢讓其重復發送規定次數呢
uj5u.com熱心網友回復:
for或while回圈里try catch,如果沒有例外,直接break回圈;如果例外,在catch里判斷是否是超時例外,是的話累加try次數,如果try次數大于3次,則break回圈,否則重新回圈try catchuj5u.com熱心網友回復:
謝謝您的答復,其實我是想集思廣益看看有什么其他的實作方式uj5u.com熱心網友回復:
遞回,方法加一個重試次數引數uj5u.com熱心網友回復:
這個重試引數定義在哪,會不會有執行緒安全問題呢?uj5u.com熱心網友回復:
讀取雙色球api的代碼,介面現在已經不可用。練手代碼,只是可用的水平
public static String getDCBallHistory() {
InputStream inputStream = null;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
StringBuffer resultBuffer = new StringBuffer();
String tempLine = null;
boolean flag = false;
int count = 0;
// System.setProperty("sun.net.client.defaultConnectTimeout", "2500");
// System.setProperty("sun.net.client.defaultReadTimeout", "3500");
while (count < 3) {
try {
URL apiUrl = new URL("http://f.apiplus.net/ssq-50.json");
HttpURLConnection httpURLConnection = (HttpURLConnection) apiUrl.openConnection();
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setReadTimeout(5000);
httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
if (httpURLConnection.getResponseCode() >= 300) {
throw new Exception(
"HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
}
while ((tempLine = reader.readLine()) != null) {
resultBuffer.append(tempLine);
}
} catch (Exception e) {
// e.printStackTrace();
flag = true;
System.out.println("direct get " + count + " times");
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (flag) {
count++;
} else {
break;
}
}
return resultBuffer.toString();
}
uj5u.com熱心網友回復:
請問怎么獲取一個積分uj5u.com熱心網友回復:
是我想的有問題?如果第1次請求失敗 flag=true了,再次回圈不重置為false,即使請求成功了也不會走breakuj5u.com熱心網友回復:
public Object req(int retryCount) {try{
// 網路請求
} catch(Exception e) { // 或者有指定某些例外
if (retryCount> 0) {
return req(--retryCount);
} else {
throw e;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/16038.html
標籤:Web 開發
上一篇:有沒有大佬知道為什么使用openfeign時,controller注入service時就報org.quartz.ObjectAlreadyExistsExcep
