13
Jul

How to abort an HTTP method before its normal completion

Following example demonstrates how to abort a HttpClient connection (based on condition) and finally close it manually

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class AbortWithHttpClient {

public final static void main(String[] args) throws Exception {
HttpClient httpclient = HttpClients.custom().build();
try {
HttpGet httpget = new HttpGet(“http://thecatapi.com/api/images/vote?api_key=xxxxxxx&sub_id=12345&image_id=bC24&score=10”);

logger.info(“Executing request ” + httpget.getURI());
HttpResponse response = httpclient.execute(httpget);
try {
logger.info(“—————————————-“);
if(response.getStatusLine().getStatusCode() != 200)
httpget.abort();
} finally {
response.close();
}
} finally {
httpclient.close();
}
}

}