我的应用程序需要响应表单Web服务,但是如果发生了套接字超时异常,则需要重试,但不超过N次(在我的情况下为3)。我用递归解决了这个问题,但我认为这可能不是最好的解决方案:
public static void process()
throws MalformedURLException, IOException {
process(1);
}
private static void process(int attempt)
throws IOException, MalformedURLException {
if (attempt <= 3) {
String data = null;
try {
data = do();
System.out.println(data);
} catch (SocketTimeoutException stoex) {
++attempt;
process(attempt);
}
}
}
do()
方法没有什么特别之处:
public static String do()
throws SocketTimeoutException,
MalformedURLException,
IOException {
URL url = new URL("www.example.com");
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// do something with response
}
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
如果有人能指出这个解决方案的一些陷阱/错误代码设计,或提出更好(通常使用)的解决方案,我很欣赏。谢谢。