来自服务器的 302 错误是对客户端的重定向指令。如果您使用的是默认配置LWP::UserAgent
,它将自动遵循重定向,最多七次。如果您没有得到成功的响应,则表明您已关闭重定向(从您发布的代码看来这不太可能,除非您省略了一些配置详细信息LWP::UserAgent
),或者您陷入了重定向循环。
您可以通过检查重定向数据来检查HTTP::Response
object:
my $resp = $ua->request($req);
# check for success, etc.
...
if ($resp->is_redirect) {
# check the number of redirects that the script has made:
say "n redirects: " . $resp->redirects;
}
使用默认的 LWP::UA 设置,在 LWP::UA 放弃之前您将获得的最大重定向数为 7。
有关重定向的更多详细信息,请致电$resp->redirects
在数组上下文中:
# @redirects is an array of HTTP::Response objects
my @redirects = $resp->redirects;
# print out the 'location' header for each Response object to track the redirection:
say "Location: " . $_->header('location') for @redirects;
# or, for more comprehensive troubleshooting, print out the whole response:
say "Response: " . $_->as_string for @redirects;
向 google.com 请求的示例输出,该请求重定向一次:
# say "n redirects: " . $resp->redirects;
n redirects: 1
# say "Location: " . $_->header('location') for @redirects;
Location: http://www.google.co.uk/?gfe_rd=cr&ei=1bg3VJikJ_HH8gfOk4GwDw
# say "Response: " . $_->as_string for @redirects;
Response: HTTP/1.1 302 Found
Cache-Control: private
Connection: close
Date: Fri, 10 Oct 2014 10:45:41 GMT
Location: http://www.google.co.uk/?gfe_rd=cr&ei=1bg3VJikJ_HH8gfOk4GwDw
Server: GFE/2.0
Content-Length: 261
Content-Type: text/html; charset=UTF-8
Alternate-Protocol: 80:quic,p=0.01
Client-Date: Fri, 10 Oct 2014 10:45:39 GMT
Client-Peer: 74.125.230.102:80
Client-Response-Num: 1
Title: 302 Moved
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.co.uk/?gfe_rd=cr&ei=1bg3VJikJ_HH8gfOk4GwDw">here</A>.
</BODY></HTML>
我的猜测是您陷入了重定向循环,这就是为什么您没有从 PHP 脚本中获得预期响应的原因。
注意:启用say
以及 Perl 5.10 及更高版本中的其他有用功能,将
use feature ':5.10';
之后在脚本的顶部use strict; use warnings;
.