0

我有以下使用代理服务器的方法。代理有时会抛出错误,我希望该方法重新尝试代理错误。我试图通过使用 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();
}
4

1 回答 1

1

发生这种情况是因为您不应该在方法中尝试 catch。该注释:@RetryOnFailure(attempts = 2, verbose = true)如果抛出异常,将执行您的方法。但是,您将所有代码封装在一个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++;
    }
 }
于 2016-07-06T17:07:04.243 回答