Add, get, set custom HttpHeader in request of HttpClient - Java @ Desk

Sunday, November 24, 2013

Add, get, set custom HttpHeader in request of HttpClient

Add, get, set custom HttpHeader in request of HttpClient

There are two ways to call the webservice using HTTP client one with Get method and other with Post method.

To add a header in HttpGet or HttpPost method, we need to use the addHeader() method which holds the key and value. Key in this has to be unique just like Map. You can add multiple headers.
HttpClient call to GET webservice: Call a web service includes following steps:

1) Create the HttpGet object by passing the URL of the webservice
2) Append the request parameters if any in the URL

HttpGet get = new HttpGet("http://localhost:8080" + "/APP_NAME/JAXRS_ADDRESS/PATH" + "?" + "REQUEST_PARAM=REQUEST_VALUE");
3) Add the headers if any as shown below

get.addHeader("userId", );
get.addHeader("Service", );
4) Make a call to web service using the HttpClient class as shown below:

HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
5) Read the response in String format as shown below

BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
    System.out.println("Here We Goooooooooooooooo " + line);
}
Complete code to call get web service:

HttpGet get = new HttpGet("http://localhost:8080" + "/APP_NAME/JAXRS_ADDRESS/PATH" + "?" + "REQUEST_PARAM=REQUEST_VALUE");
get.addHeader("userId", );
get.addHeader("Service", );
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
    System.out.println("Here We Goooooooooooooooo " + line);
}
To get the request param from the URL in a get web service, you need to use below code as an argument in the web service method :
@QueryParam(REQUEST_PARAM) String requestParam
To get the header values in the web service, you need to use below code as an argument in the web service method :
@Context HttpHeaders httpHeader
Make a call to 
httpHeader.getRequestHeader("userId")






No comments:

Post a Comment