Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache HttpClient 4.0-beta2 httppost, how to add a referer?

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);
like image 324
Lasoldo Solsifa Avatar asked Jul 19 '09 19:07

Lasoldo Solsifa


Video Answer


1 Answers

Any reason not to do:

httppost.addHeader("Referer", referer);

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

like image 183
Jon Skeet Avatar answered Oct 18 '22 09:10

Jon Skeet