- Multipart Upload
- Custom SSL Context
- Multiple Threads
- Cookies Management
- Form-Based Login
- Proxy Authentication
- Using Proxy
- User Authentication
- Interceptors
- Aborting a Request
- Closing Connection
- Response Handlers
- Http Post Request
- Http Get Request
- Environment Setup
- Overview
- Home
Apache HttpClient Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Apache HttpCpent - Response Handlers
Processing the HTTP responses using the response handlers is recommended. In this chapter, we are going to discuss how to create response handlers and how to use them to process a response.
If you use the response handler, all the HTTP connections will be released automatically.
Creating a response handler
The HttpCpent API provides an interface known as ResponseHandler in the package org.apache.http.cpent. In order to create a response handler, implement this interface and override its handleResponse() method.
Every response has a status code and if the status code is in between 200 and 300, that means the action was successfully received, understood, and accepted. Therefore, in our example, we will handle the entities of the responses with such status codes.
Executing the request using response handler
Follow the steps given below to execute the request using a response handler.
Step 1 - Create an HttpCpent Object
The createDefault() method of the HttpCpents class returns an object of the class CloseableHttpCpent, which is the base implementation of the HttpCpent interface. Using this method create an HttpCpent object
CloseableHttpCpent httpcpent = HttpCpents.createDefault();
Step 2 - Instantiate the Response Handler
Instantiate the response handler object created above using the following pne of code −
ResponseHandler<String> responseHandler = new MyResponseHandler();
Step 3 - Create a HttpGet Object
The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI.
Create an HttpGet request by instantiating the HttpGet class and by passing a string representing the URI as a parameter to its constructor.
ResponseHandler<String> responseHandler = new MyResponseHandler();
Step 4 - Execute the Get request using response handler
The CloseableHttpCpent class has a variant of execute() method which accepts two objects ResponseHandler and HttpUriRequest, and returns a response object.
String httpResponse = httpcpent.execute(httpget, responseHandler);
Example
Following example demonstrates the usage of response handlers.
import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.cpent.ResponseHandler; import org.apache.http.cpent.methods.HttpGet; import org.apache.http.impl.cpent.CloseableHttpCpent; import org.apache.http.impl.cpent.HttpCpents; import org.apache.http.util.EntityUtils; class MyResponseHandler implements ResponseHandler<String>{ pubpc String handleResponse(final HttpResponse response) throws IOException{ //Get the status of the response int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); if(entity == null) { return ""; } else { return EntityUtils.toString(entity); } } else { return ""+status; } } } pubpc class ResponseHandlerExample { pubpc static void main(String args[]) throws Exception{ //Create an HttpCpent object CloseableHttpCpent httpcpent = HttpCpents.createDefault(); //instantiate the response handler ResponseHandler<String> responseHandler = new MyResponseHandler(); //Create an HttpGet object HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/"); //Execute the Get request by passing the response handler object and HttpGet object String httpresponse = httpcpent.execute(httpget, responseHandler); System.out.println(httpresponse); } }
Output
The above programs generate the following output −
<!DOCTYPE html> <!--[if IE 8]><html class = "ie ie8"> <![endif]--> <!--[if IE 9]><html class = "ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html lang = "en-US"> <!--<![endif]--> <head> <!-- Basic --> <meta charset = "utf-8"> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes"> <pnk href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel = "stylesheet" type = "text/css" /> <pnk rel = "stylesheet" href = "/questions/css/home.css?v = 3" /> <script src = "/questions/js/jquery.min.js"></script> <script src = "/questions/js/fontawesome.js"></script> <script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . <script> window.dataLayer = window.dataLayer || []; function gtag() {dataLayer.push(arguments);} gtag( js , new Date()); gtag( config , UA-232293-17 ); </script> </body>Advertisements