我有一个perl脚本将数据发布到我在php中编写的Web服务...
这是代码:
use LWP::UserAgent;
my $ua = LWP::UserAgent->new;
my $server_endpoint = "http://example.com/";
my $req = HTTP::Request->new(POST => $server_endpoint);
$req->header('content-type' => 'application/json');
$req->header('x-auth-token' => 'kfksj48sdfj4jd9d');
# add POST data to HTTP request body
my $post_data = '{ "name": "Dan", "address": "NY" }';
$req->content($post_data);
my $resp = $ua->request($req);
if ($resp->is_success) {
my $message = $resp->decoded_content;
print "Received reply: $message\n";
}
else {
print "HTTP POST error code: ", $resp->code, "\n";
print "HTTP POST error message: ", $resp->message, "\n";
}
当我发送请求时,我得到了这个回复:
HTTP POST error code: 302
HTTP POST error message: Found
问题:
提前致谢。
答案 0 :(得分:3)
来自服务器的302错误是对客户端的重定向指令。如果您使用LWP::UserAgent
的默认配置,它将自动跟踪重定向,最多七次。如果您没有得到成功的响应,则表明您已关闭重定向(从您发布的代码看起来不太可能,除非您省略了LWP::UserAgent
的某些配置详细信息),或者你陷入了重定向循环。
您可以通过检查HTTP::Response
对象来检查重定向数据:
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放弃之前获得的最大重定向数。
通过在数组上下文中调用$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脚本中获得预期的响应。
注意:要从Perl 5.10及更高版本启用say
和其他有用的功能,请输入
use feature ':5.10';
在use strict; use warnings;
之后的脚本顶部。