How to access HTTP headers from a given url?

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.

Answers


use LWP::UserAgent;

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

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.


Need Your Help

Using Stored procedures in ASP.net MVC?

asp.net-mvc entity-framework asp.net-mvc-4 ado.net

Guys I am trying to learn MVC and I want to use stored procedures to perform all CRUD operations in MVC framework. I have googled for tutorials and everything, but all the tutorials are using that

RSpec have_tag failing even when tag is present?

ruby-on-rails ruby rspec

Currently doing the Ruby On Rails Tutorial by Michael Hartl, and am starting on test-driven development. The tutorial demands that tests be written to ensure that the right titles are present on our

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.