[英]LWP::UserAgent - HTTP::Request
If I do this 如果我这样做
#!/usr/local/bin/perl
use warnings;
use 5.014;
use LWP::UserAgent;
my $ua = LWP::UserAgent->new();
my $res = $ua->get( 'http://www.perl.org' );
I can call HTTP::Response
methods like this 我可以像这样调用HTTP::Response
方法
say $res->code;
Is it somehow possible to call HTTP::Request
methods from the $res
object or needs that the creation of a HTTP::Request
object explicitly? 是否有可能从$res
对象调用HTTP::Request
方法或者需要显式创建HTTP::Request
对象?
my $ua = LWP::UserAgent->new();
my $method;
my $res = $ua->get( 'http://www.perl.org' );
$ua->add_handler( request_prepare => sub { my( $request, $ua, $h ) = @_; $method = $request->method; }, );
say $method; # Use of uninitialized value $method in say
To get the request object that was created for you: 获取为您创建的请求对象:
my $response = $ua->get('http://www.example.com/');
my $request = ($response->redirects, $response)[0]->request;
Might be easier just to create a request object yourself 可能更容易自己创建一个请求对象
use HTTP::Request::Common qw( GET );
my $request = GET('http://www.example.com/');
my $response = $ua->request($request);
The HTTP::Request
is used internally by LWP::UserAgent
and if they would return it via get
or post
-Methods it would already be too late since the request is already done. HTTP::Request
由LWP::UserAgent
在内部使用,如果他们通过get
或post
-Methods返回它,那么因为请求已经完成已经太晚了。 But they have apparently foreseen the need for accessing the request object so they implemented callbacks so you can modify the request before it is sent: 但是他们显然已经预见到需要访问请求对象,因此他们实现了回调,因此您可以在发送请求之前修改请求:
$ua->add_handler(request_prepare => sub {
my($request, $ua, $h) = @_;
# $request is a HTPP::Request
$request->header("X-Reason" => "just checkin");
});
So if you need to access the request-object without creating it and setting it up - callbacks are the way to go. 因此,如果您需要访问请求对象而不创建它并进行设置 - 回调是可行的方法。
Which HTTP::Request
methods do you want to call? 您要调用哪种HTTP::Request
方法? And on which request object? 以及哪个请求对象? The last request made by $ua
? $ua
的最后一个请求?
As far as I can tell, LWP::get
does not save the last request created/sent anywhere. 据我所知, LWP::get
不保存在任何地方创建/发送的最后一个请求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.