0

I am looking for a way to get http headers from a given url. I tried the below code but it is not working:

#!/usr/bin/perl

#use warnings;
#use strict;
use LWP::UserAgent;

my $ua  = LWP::UserAgent->new;
my $res = $ua->get("http://cpan.org");
print $res->header('Content-Length');

The above code prints nothing. So, where am I going wrong here or is there any better way to access headers.

4
  • 2
    Your script returned 8019 for me... Commented Sep 9, 2012 at 21:32
  • @Kenosis: /facepalm was not connected to the internet while using this script. Anyways how can one extract the user-agent field. I tried $res->header('agent') but it didn't worked or I have to explicitly set User-Agent and than retrieve it. Commented Sep 9, 2012 at 21:36
  • 6
    There's no such thing as a Agent header in an HTTP response. Commented Sep 9, 2012 at 21:43
  • In case the following may be helpful: How to set User-Agent with LWP? Commented Sep 9, 2012 at 21:52

2 Answers 2

3

You should check the result of the request before you assume that you can use it as if it worked:

use v5.10;

use LWP::UserAgent;

my $ua  = LWP::UserAgent->new;
my $res = $ua->get("http://444.cpan.org");

if( $res->is_success ) {
    say "Content length is ", $res->header('Content-Length');
    }
else {
    say "Error! ", $res->code;
    }

Remember that a Content-Length header does not mean that you had a successful request. An error response might still contain a message body, which would have a length.

Sign up to request clarification or add additional context in comments.

Comments

1
use LWP::UserAgent;

my $ua  = LWP::UserAgent->new;
my $res = $ua->get("http://cpan.org");
print $res->headers->as_string;

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.