views:

1984

answers:

1

I'm trying to add a referer to an http post in Apache HttpClient (httpclient-4.0-beta2).

I found some sample code that does this. The code works, but I'm wondering if there is not a simpler, more straightforward way to add the referer than using the (ominously named) addRequestInterceptor, which appears to take an (yikes!) inner class as a parameter.

The code in question begins below with "// add the referer header". I'm a novice, and this code is doing several things that I don't understand. Is this really the simplest way to add a referer to my http post?

Thanks for any pointers.

// initialize request parameters
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("firstName", "John"));
formparams.add(new BasicNameValuePair("lastName", "Doe"));

// set up httppost
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(submitUrl);
httppost.setEntity(entity);

// create httpclient
DefaultHttpClient httpclient = new DefaultHttpClient();

// add the referer header, is an inner class used here?
httpclient.addRequestInterceptor(new HttpRequestInterceptor()
{   
    public void process(final HttpRequest request, 
                        final HttpContext context) throws HttpException, IOException
    {
        request.addHeader("Referer", referer);
    }
});

// execute the request
HttpResponse response = httpclient.execute(httppost);
+3  A: 

Any reason not to do:

httppost.addHeader("Referer", referer);

? HttpPost subclasses (indirectly) AbstractHttpMessage so you should be able to just add headers that way.

Jon Skeet
Thank you very much for this help. I'm pretty sure that I tried something like this first, and on failing, began searching for another way. Yet, when I try it now it works first time! :) Probably a small mistake I made that led me astray (I won't admit how many days I've been working on it...).
Lasoldo Solsifa