在Perl中发送HTTP请求

时间:2011-07-01 12:14:00

标签: windows perl http

如何在Windows上的Perl中发送这样的请求?

GET /index.html HTTP/1.1
Host: www.example.org
Cookie: test=quest

2 个答案:

答案 0 :(得分:9)

您可以使用套接字执行此操作:

use IO::Socket;
my $sock = new IO::Socket::INET (
                                 PeerAddr => 'www.example.org',
                                 PeerPort => '80',
                                 Proto => 'tcp',
                                );
die "Could not create socket: $!\n" unless $sock;
print $sock "GET /index.html HTTP/1.0\r\n";
print $sock "Host: www.example.org\r\n";
print $sock "Cookie: test=quest\r\n\r\n";
print while <$sock>;
close($sock);

但您可能想要考虑使用LWP(libwww-perl):

use LWP::UserAgent;
$ua = LWP::UserAgent->new;

$req = HTTP::Request->new(GET => 'http://www.example.org/index.html');
$req->header('Cookie' => 'test=quest');

# send request
$res = $ua->request($req);

# check the outcome
if ($res->is_success) { print $res->decoded_content }
else { print "Error: " . $res->status_line . "\n" }

您可以尝试阅读LWP cookbook以了解LWP。

答案 1 :(得分:3)

LWP::UserAgent是正常的起点。如果要提前设置特定的cookie值,可以手动传入HTTP::Cookies对象。