How can I use Perl to send and HTTP request with a cookie?

后端 未结 2 1546
眼角桃花
眼角桃花 2020-12-31 12:16

I am new to Perl and I want to write a Perl program that:

  • creates an HTTP request
  • sends it to any URL (e.g. http://www.google.com )
  • includes
相关标签:
2条回答
  • 2020-12-31 12:57

    Start with LWP::UserAgent and HTTP::Cookies

    0 讨论(0)
  • 2020-12-31 13:03

    As mentioned cookies are in HTTP::Cookies:

    • You need to create a cookie jar

    • You set the value of the cookies to put in the jar

    • You then associate that jar with your user agent

    For example:

    my $ua = LWP::UserAgent->new;
    my $cookies = HTTP::Cookies->new();
    $cookies->set_cookie(0,'cookiename', 'value','/','google.com',80,0,0,86400,0);
    $ua->cookie_jar($cookies);
    # Now make your request
    

    set_cookie has a rather large number of arguments:

    set_cookie( $version, $key, $val, $path, $domain, $port, $path_spec, $secure, $maxage, $discard, \%rest )

    This is because the cookie jar is designed from the point of view of a browser (a UserAgent), rather than a single request. This means not all the arguments are so important in this case.

    The ones you need to get right are $key, $val, $path, $domain, $port.

    Regarding the:

    500 Can't connect to www.google.com:80 (Bad hostname 'www.google.com')

    It means that LWP can't lookup the address for Google. Are you behind a web proxy? If so you will need to set your proxy in the UA too using something like:

    $ua->proxy(['http', 'https'], 'http://proxyhost.my.domain.com:8080/');

    0 讨论(0)
提交回复
热议问题