我有以下方法使用代理從服務器檢索信息。有時由於錯誤的代理,我得到SocketException
,SSLException
,SSLHandshakeException
或ConnectException
重試對某些例外的方法
正如你在我已經使用catch (IOException ioe)
我的方法看,我需要做的是,爲了獲得服務器響應的內容,如果服務器返回什麼而不是代碼200.
如何在上述例外的情況下使方法重試?
public String getMeta() throws IOException
{
HttpsURLConnection con = null;
InputStream is = null;
StringWriter writer = new StringWriter();
try
{
String url = "https://api.myapp.com/meta";
URL urlObj = new URL(url);
if (useProxy && fullProxy)
{
myapp.Proxy proxyCustom = getRandomProxy();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyCustom.getProxyIp(), proxyCustom.getProxyPort()));
con = (HttpsURLConnection) urlObj.openConnection(proxy);
}
else
{
con = (HttpsURLConnection) urlObj.openConnection();
}
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setRequestProperty("host", urlObj.getHost());
con.setRequestProperty("Connection", "Keep-Alive");
int responseCode = 0;
responseCode = con.getResponseCode();
is = con.getInputStream();
writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
}
catch (IOException ioe)
{
if (con instanceof HttpsURLConnection)
{
HttpsURLConnection httpConn = (HttpsURLConnection) con;
int statusCode = httpConn.getResponseCode();
if (statusCode != 200)
{
is = httpConn.getErrorStream();
writer = new StringWriter();
IOUtils.copy(is, writer, "UTF-8");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return writer.toString();
}
使用循環或遞歸。如果你想避免那些東西和無盡的遞歸/循環,沒有額外的邏輯,只需將try-block中的所有內容都放到一個新的方法中即可。然後你可以再打一次電話。 – HopefullyHelpful
'我如何使方法重試'您想重試一次,還是不斷重試,直到沒有異常拋出? – copeg
@copeg我希望有一個簡單的方法來設置它應該重試的時間,但它太複雜了,我只會嘗試一次。 – Arya