使用LWP发送纯字符串请求

时间:2011-05-02 10:48:51

标签: perl http lwp lwp-useragent

要从某个网站获得回复,我必须提供一个确切的请求字符串HTTP / 1.1。我用telnet尝试了那个,它给了我想要的响应(重定向,但我需要它)。

但是当我尝试向HTTP::Request->parse()提供相同的请求字符串时,我只收到消息400 URL must be absolute

我不确定这是网站还是LWP给我这个,因为正如我所说,回复与telnet一致。

这是代码:

my $req = "GET / HTTP/1.1\n".
  "Host: www.example-site.de\n".
  "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1\n".
  "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n".
  "Accept-Language: en-us,en;q=0.5\n".
  "Accept-Encoding: gzip, deflate\n".
  "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n".
  "Keep-Alive: 115\n".
  "Connection: keep-alive\n";

# Gives correct request string
print HTTP::Request->parse($req)->as_string;

my $ua = LWP::UserAgent->new( cookie_jar => {}, agent => '' );
my $response = $ua->request(HTTP::Request->parse($req));

# 400 error
print $response->as_string,"\n";

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

如果请求中没有指定架构,

LWP::UserAgent会因您收到错误而死亡。可能需要它才能正确使用它。

因此,要使其正常工作,您需要为您的请求指定完整网址:

my $req_str = "GET http://www.example.de/\n".
  "User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:2.0.1) Gecko/20100101 Firefox/4.0.1\n".
  "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\n".
  "Accept-Language: en-us,en;q=0.5\n".
  "Accept-Encoding: gzip, deflate\n".
  "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n".
  "Keep-Alive: 115\n".
  "Connection: keep-alive\n";

答案 1 :(得分:0)

在我看来,解析请求并非100%往返安全,这意味着您无法将响应反馈回请求。

看起来像一个乍一看的错误,但模块已经出了很长时间......另一方面,我甚至不知道你可以使用这个模块来解析请求,所以也许它没有经过如此好的测试

以下测试用例应该指出您的问题,即URL未正确汇编以便提供给$req->request方法。

use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use Test::More;

my $host = 'www.example.com';
my $url = '/bla.html';

my $req = <<"EOS";
GET $url HTTP/1.1
Host: $host
EOS

# (1) parse the request
my $reqo = HTTP::Request->parse($req);
isa_ok $reqo, 'HTTP::Request';
diag explain $reqo;
diag $reqo->as_string;

# (2) construct the request
my $reqo2 = HTTP::Request->new( GET => "http://$host$url" );
isa_ok $reqo2, 'HTTP::Request';
diag explain $reqo2;
diag $reqo2->as_string;

is $reqo->uri, $reqo2->uri, 'both URLs are identical';

my $ua = LWP::UserAgent->new( cookie_jar => {}, agent => '' );
for ( $reqo, $reqo2 ) {
    my $response = $ua->request( $_ );
    diag $response->as_string,"\n";
}

done_testing;

答案 2 :(得分:0)

好的,我是用套接字做的。毕竟,我有HTTP请求,并希望得到简单的响应。这里是感兴趣的人的代码:

use IO::Sockets;

my $sock = IO::Socket::INET->new(
    PeerAddr => 'www.example-site.de',
    PeerPort => 80, 
    Proto => 'Tcp',
);
die "Could not create socket: $!\n" unless $sock;

print $sock, $req;

while(<$sock>) {
    # Look for stuff I need
}

close $sock;

记住离开while非常重要,因为HTTP响应不会以EOF结尾。

相关问题