-1
我需要嘗試連接到字符串request_url
中的url。如果連接超時發生,我需要再次重試2次,然後再調用另一個url(ans.getUrl(2)
)並重復相同的邏輯。這是我的代碼片段。任何人都可以幫我解決我需要在這裏使用的邏輯嗎?當URLConnection超時發生時,需要嘗試再次連接兩次,然後再更改url並再次嘗試
//ans.getUrl returns a url based on the int parameter you send. It can only be 1 and 2.
String request_url= ans.getUrl(1);
try {
URL url;
URLConnection urlConn;
DataInputStream input;
//URL Creation:
url = new URL(request_url);
// URL connection channel.
urlConn = url.openConnection();
urlConn.setConnectTimeout(2000);
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
// Get response data.
input = new DataInputStream(urlConn.getInputStream());
String str;
System.out.println("Response XML::: ");
while (null != ((str = input.readLine()))) {
System.out.println("XML:: "+str);
//Write to temp file for parsing
FileWriter fstream = new FileWriter("response.xml", true);
BufferedWriter out = new BufferedWriter(fstream);
out.write(str+"\n");
//Close the output stream
out.close();
}
//Close input
input.close();
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: "
+ e.getMessage());
} catch (IOException e) {
System.err.println("Caught IOException: "
+ e.getMessage());
}
您可能不需要這樣做。在底層,底層的TCP套接字在引發異常之前已經完成了至少3次連接嘗試。你知道嗎? – EJP
沒有。我不是。謝謝。我會仔細看看的 – Srinivas