8

When specifying custom header containing underscores using HTTP::Request from LWP::UserAgent, the underscores are changed to hyphens:

use LWP::UserAgent;

my $rq = HTTP::Request->new("GET", "http://cpan.org");
$rq->header("X-FOO_BAR", "xyzzy");
print $rq->as_string;

outputs:

GET http://cpan.org
X-FOO-BAR: xyzzy

Is there a way to turn this behavior off?

  • perl v5.26.2
  • LWP:UserAgent 1.9601
  • linux 4.17.8-1-ARCH

2 Answers 2

16

Try naming the header with a leading :, as per the documentation in HTTP::Headers under "NON-CANONICALIZED FIELD NAMES":

The header field name spelling is normally canonicalized including the '_' to '-' translation. There are some application where this is not appropriate. Prefixing field names with ':' allow you to force a specific spelling.

2
  • Yup, I was just about to post ... :) tested (v5.16)
    – zdim
    Commented Aug 2, 2018 at 21:53
  • That's a dusty corner of CPAN that I didn't know about.Thank you!
    – Borodin
    Commented Aug 2, 2018 at 23:22
0

I had the same problem too while trying to write out a location in a pages header via CGI::Session. I fixed it by replacing the underscore with %5f and it worked for me. In your case this might work:

$rq->header('X-FOO%5fBAR', "xyzzy");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.