我有以下使用代理服务器的方法。代理有时会抛出错误,我希望该方法重新尝试代理错误。我试图通过使用jcabi-aspects库来做到这一点,但它似乎没有做它应该做的事情。我没有看到任何关于失败的详细信息。任何帮助实现这一点是值得赞赏的。
@RetryOnFailure(attempts = 2, verbose = true)
public String update(String lastActivityDate)
{
StringBuffer response = new StringBuffer();
try
{
String url = "https://api.somesite.com/updates";
URL urlObj = new URL(url);
HttpsURLConnection con = null;
if (useProxy)
{
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();
}
// add reuqest header
con.setRequestMethod("POST");
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");
String urlParameters = "{}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
// System.out.println("\nSending 'POST' request to URL : " + url);
// System.out.println("Post parameters : " + urlParameters);
// System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
}
in.close();
// print result
// System.out.println(response.toString());
}
catch (Exception e)
{
e.printStackTrace();
}
return response.toString();
}
答案 0 :(得分:1)
这种情况正在发生,因为您不应该尝试捕获方法。该注释:@RetryOnFailure(attempts = 2, verbose = true)
将执行您的方法,如果它抛出一个exeption。但是,您将所有代码封装在try catch
块中。
使用@RetryOnFailure注释注释您的方法,如果是 方法中的异常,其执行将重复几次:
此外,您可能希望在重试之间添加延迟:@RetryOnFailure(attempts = 2, delay = 2000, verbose = true)
(默认为以毫秒为单位)
编辑:如果您不想将其配置为与jcabi一起使用,那么您可以执行以下操作:
int retries = 0;
Boolean success = false;
while(retries <x && ! success){ // you need to set x depending on how many retries you want
try{
// your code goes here
success = true;
}
catch{
retries++;
}
}