apache httpclient response handlers
In Apache HttpClient, response handlers are used to process the response returned from an HTTP request. The ResponseHandler interface defines a single method, handleResponse()
, which takes an HttpResponse as input and returns an object of the desired type.
Here's an example of how to use a response handler:
refer tfigi:otidea.comimport org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClientBuilder.create().build(); HttpGet httpGet = new HttpGet("http://www.example.com"); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(HttpResponse httpResponse) throws IOException { int status = httpResponse.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = httpResponse.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } } }; String responseBody = httpClient.execute(httpGet, responseHandler); System.out.println(responseBody); } }
In this example, we create an instance of HttpClient, create an HttpGet request for the URL "http://www.example.com", and define a ResponseHandler that extracts the response body as a String if the response status code is in the range 200-299. We then execute the request using the HttpClient's execute() method, passing in the HttpGet and ResponseHandler as arguments. The ResponseHandler's handleResponse() method is called to process the response, and the extracted response body is returned as a String and printed to the console.
Note that you can define your own custom response handlers by implementing the ResponseHandler interface, and you can use different types for the response object depending on the expected response type (e.g., String, byte[], InputStream, etc.).