问题描述
我是 Perl 的新手,我想编写一个 Perl 程序:
I am new to Perl and I want to write a Perl program that:
- 创建一个 HTTP 请求
- 将其发送到任何网址(例如 http://www.google.com )
- 在请求中包含一个 cookie
- 在文件中记录 http 响应代码
我已经试过了:
#!/usr/bin/perl
require HTTP::Request;
require LWP::UserAgent;
$request = HTTP::Request->new(GET => 'http://www.google.com/');
$ua = LWP::UserAgent->new;
$ua->cookie_jar({file => "testcookies.txt",autosave =>1});
$response = $ua->request($request);
if($response->is_success){
print "sucess\n";
print $response->code;
}
else {
print "fail\n";
die $response->code;
}
请告诉如何在请求"中设置 cookie,即
pls tell how to set cookie in 'request' ie
如何在发送 HTTP::Request 时设置 cookie
how to set a cookie when we send HTTP::Request
我期待的是:
$request = HTTP::Request->new(GET => 'http://www.google.com/');
$ua = LWP::UserAgent->new;
$ua->new CGI::Cookie(-name=>"myCookie",-value=>"fghij");
这可能吗??
推荐答案
如前所述,cookie 位于 HTTP::Cookies 中:
As mentioned cookies are in HTTP::Cookies:
您需要创建一个 cookie jar
You need to create a cookie jar
您设置要放入 jar 的 cookie 的值
You set the value of the cookies to put in the jar
然后您将该 jar 与您的用户代理相关联
You then associate that jar with your user agent
例如:
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
有相当多的参数:
set_cookie( $version, $key, $val, $path, $domain, $port,$path_spec, $secure, $maxage, $discard, \%rest )
这是因为 cookie jar 是从浏览器(用户代理)的角度设计的,而不是从单个请求的角度设计的.这意味着在这种情况下,并非所有参数都如此重要.
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.
您需要正确处理的是 $key、$val、$path、$domain、$port.
The ones you need to get right are $key, $val, $path, $domain, $port.
关于:
500 无法连接到 www.google.com:80(错误的主机名www.google.com")
这意味着 LWP 无法为 Google 查找地址.您是否支持 Web 代理?如果是这样,您也需要使用以下内容在 UA 中设置代理:
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/');
$ua->proxy(['http', 'https'], 'http://proxyhost.my.domain.com:8080/');
这篇关于如何使用 Perl 发送带有 cookie 的 HTTP 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!