Force retry on specific http status code

后端 未结 2 1496
臣服心动
臣服心动 2021-02-01 09:29

Dealing with a specific website, sometimes I receive a http response with status code 403. I wanted to re-execute the request in such cases (because, in my specific situation, t

相关标签:
2条回答
  • 2021-02-01 09:49

    You can do it by manually checking the status code, something like this:

    CloseableHttpResponse response = null;
    boolean success = false;
    while(!success) {
        response = client.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        success = (status == 200);
        if (!success) {
            if(status == 403) {
                Thread.sleep(2000); // wait 2 seconds before retrying
            } else {
                throw new RuntimeException("Something went wrong: HTTP status: " + status);
            }
        }
    }
    String contents = EntityUtils.toString(response.getEntity());
    response.close();
    
    // ....
    
    System.out.println(contents);
    

    You would need to add some things like retrying a predefined number of times before throwing a final exception and catching some checked exceptions (like the InterruptedException thrown by Thread.sleep()), but basically the code shows the main idea.

    0 讨论(0)
  • 2021-02-01 09:59

    Try using a custom ServiceUnavailableRetryStrategy

    CloseableHttpClient client = HttpClients.custom()
            .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {
                @Override
                public boolean retryRequest(
                        final HttpResponse response, final int executionCount, final HttpContext context) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    return statusCode == 403 && executionCount < 5;
                }
    
                @Override
                public long getRetryInterval() {
                    return 0;
                }
            })
            .build();
    
    0 讨论(0)
提交回复
热议问题