来自HTTP POST操作的错误代码302

时间:2014-10-10 09:50:38

标签: perl post http-status-code-302

我有一个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

问题:

  • 我怎样才能摆脱这个错误,或者这甚至是一个错误,虽然它说发现了?
  • 如何获得帖子的返回值?
  • 发布数据的正确方法是什么? (上面的代码是copied from this site。 我的php网站获取发布数据和echo,或者只是将其打印为返回。)

提前致谢。

1 个答案:

答案 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&amp;ei=1bg3VJikJ_HH8gfOk4GwDw">here</A>.
</BODY></HTML>

我的猜测是你陷入了重定向循环,这就是为什么你没有从PHP脚本中获得预期的响应。

注意:要从Perl 5.10及更高版本启用say和其他有用的功能,请输入

use feature ':5.10';

use strict; use warnings;之后的脚本顶部。