我有以下方法,它使用代理从服务器检索信息。有时由于糟糕的代理,我会得到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();
}发布于 2016-07-07 03:15:16
如果出现上述异常,如何让方法重试?
下面显示的一种方法是让getMeta方法实际抛出IOException。然后,由于捕获到任何异常,您可以让caller方法递归地调用自身。
我希望有一种简单的方法来设置重试的次数
为了能够调用该方法的n次数,请将该次数作为参数传入,并相应地处理停止条件逻辑。例如:
public String caller(int total) throws IOException{
return callerImpl(1, total);
}
public String callerImpl(int current, int total) throws IOException{
try{
return getMeta();
}catch(IOException e){
current++;
if ( current > total ){
throw e;//or return null or empty string, depending upon upstream requirements
}
return callerImpl(current, total);
}
return null;
}在getMeta中:
try{
....
}catch(IOException io){
//log or handle io
throw io;
}注上面并没有处理抛出的异常的日志记录/逻辑,您可能希望以某种方式处理这些异常。
https://stackoverflow.com/questions/38231785
复制相似问题