How to add Request Interceptor
Commons Http Client is a HTTP agent implementation in java supporting
client-side authentication, HTTP state management and HTTP connection management.
This requires the libraries httpclient-4.1.2.jar, httpcore-4.1.2.jar,
httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and
commons-logging-1.1.1.jar to be in classpath.
The following example shows how to create a request Interceptor.
package com.bethecoder.tutorials.commons_httpclient;
import java.io.IOException;
import java.util.Date;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HttpContext;
public class RequestInterceptorTest {
/**
* @param args
* @throws IOException
* @throws ClientProtocolException
*/
public static void main ( String [] args ) throws ClientProtocolException, IOException {
DefaultHttpClient httpclient = new DefaultHttpClient () ;
HttpGet httpget = new HttpGet ( "http://localhost:8080/HTTP_TEST_APP/print_headers.jsp" ) ;
System.out.println ( "Requesting : " + httpget.getURI ()) ;
try {
httpclient.addRequestInterceptor ( new HttpRequestInterceptor () {
@Override
public void process ( HttpRequest request, HttpContext context )
throws HttpException, IOException {
request.addHeader ( "Author" , "Sudhakar KV" ) ;
request.addHeader ( "Triggered-On" , new Date () .toString ()) ;
String agent = request.getFirstHeader ( "User-Agent" ) .getValue () ;
request.addHeader ( "User-Agent-US" , agent.toUpperCase ()) ;
}
}) ;
ResponseHandler<String> responseHandler = new BasicResponseHandler () ;
String responseBody = httpclient.execute ( httpget, responseHandler ) ;
System.out.println ( "responseBody : " + responseBody ) ;
} finally {
httpclient.getConnectionManager () .shutdown () ;
}
}
}
A simple Web Application which prints the request headers through JSP.
It gives the following output,