Question

I have taken over some perl code and been asked to add a keep-alive header to the LWP post that happens.

Google tells me how to do this for certain setups, but I can't see how to do it for the way this code has been written. All the info I can find works on the basis of creating the LWP object, then creating the POST and parameters, then adding the headers, then actually POSTING the request, however in the code I have to deal with, the creating of the POST, adding the headers and sending are all in one line:

my $ua = LWP::UserAgent->new;
my $response = $ua->post( $URL, ['parm1'=>'val1']);

How/where can I add the headers in this setup, or do I need to re-write as per the examples I have found?

Was it helpful?

Solution

The LWP::UserAgent page tells you how to do this. You would set the handler request_prepare on the user agent object. That will pass you in the request object before it posts.

Actually, anything you put as a list of key-value pairs before the key 'Content' followed by the structure that you want to post, will translate into headers, per HTTP::Request::Common::POST

 $ua->post( $URL, keep_alive => 1, Content => ['parm1'=>'val1']);

Or without the content tag, if you put the structure first, you can put header key-value pairs after:

 $ua->post( $URL, ['parm1'=>'val1'], keep_alive => 1 );

OTHER TIPS

Did they really asked you to add a keep-alive header only, or did they ask you to support keep alive, e.g. multiple HTTP requests within the same TCP connection. In the latter case you should use (according to the documentation of LWP::UserAgent):

my $ua = LWP::UserAgent->new( keep_alive => 10 );
$ua->get('http://foo.bar/page1');
$ua->get('http://foo.bar/page2');   # reuses connection from previous request

In this case it will keep at most 10 connections open at the same time. If you only do requests do the same site you can also set it to 1 so that it reuses the same TCP connection for all requests.

A Keep-Alive header has no meaning, what keep_alive => 1 within the user agent does is set up a connection cache and add a "Connection: keep-alive" header (with HTTP/1.1 keep-alive is implicite, so it does not need to add the header for HTTP/1.1 requests).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top