Error code 302 from HTTP POST operation

五迷三道 提交于 2019-12-05 19:19:52

A 302 error from a server is a redirection instruction to the client. If you are using the default configuration of LWP::UserAgent, it will automatically follow redirects up to a maximum of seven times. If you are not getting a successful response, it suggests that either you've got redirects turned off (which looks unlikely from the code you've posted, unless you've omitted some configuration details for LWP::UserAgent), or that you're getting stuck in a redirect loop.

You can examine the redirection data by checking the 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;
}

With the default LWP::UA settings, seven is the maximum number of redirects you'll get before LWP::UA gives up.

More details on the redirects is available by calling $resp->redirects in array context:

# @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;

Example output for a request to google.com, which redirects once:

# 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>

My guess is that you've got stuck in a redirect loop, and that is why you're not getting the expected response back from your PHP script.

NB: to enable say and other useful features from Perl 5.10 and later, put

use feature ':5.10';

at the top of your script after use strict; use warnings;.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!