Hello,

I am trying to rewrite the User-Agent header using the request_preprepare handler. For testing purposes, I have a webserver set up that redirects / to /dog, /dog to /cat, and /cat to /cat/.

I have the following code:

use strict; use warnings; use LWP::UserAgent; my $url = "http://127.0.0.1"; my $ctr = 0; my $ua = LWP::UserAgent->new(); $ua->agent('BOGUS'); $ua->add_handler( request_preprepare => sub { $ua->agent("TEST $ctr"); + print "User-Agent: ", $ua->agent, "\n"; $ctr++; }); my $response = $ua->get($url);

Running the above results in the following output:

User-Agent: TEST 0
User-Agent: TEST 1
User-Agent: TEST 2
User-Agent: TEST 3

But the webserver log show the following:

127.0.0.1 - - 12/Aug/2014:23:06:09 -0400 "GET / HTTP/1.1" 302 204 "-" "TEST 0"
127.0.0.1 - - 12/Aug/2014:23:06:09 -0400 "GET /dog HTTP/1.1" 302 204 "-" "TEST 0"
127.0.0.1 - - 12/Aug/2014:23:06:09 -0400 "GET /cat HTTP/1.1" 302 205 "-" "TEST 0"
127.0.0.1 - - 12/Aug/2014:23:06:09 -0400 "GET /cat/ HTTP/1.1" 200 669 "-" "TEST 0"

It sets "TEST 0" as the initial User-Agent for the request for / (correctly replacing "BOGUS"), but it never increments for /dog, /cat, or /cat/ although it appears the handler is being called.

What am I doing wrong?

I can make this work by setting max_redirects to 0 and doing the redirect work manually by creating new LWP::UserAgent objects, but that is less elegant.

Thanks!

In reply to User-Agent in LWP::UserAgent by msel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.