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
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.