Force retry on specific http status code

后端 未结 2 1497
臣服心动
臣服心动 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.

提交回复
热议问题