我正在使用 urllib2 将数据发布到表单。问题是表单回复了 302 重定向。根据 Python HTTPRedirectHandler 重定向处理程序将获取请求并将其从 POST 转换为 GET,并遵循 301 或 302。我想保留 POST 方法和传递给 opener 的数据。我通过简单地将 data=req.get_data() 添加到新请求来尝试自定义 HTTPRedirectHandler,但没有成功。

我确信以前已经做过这样的事情,所以我想我应该发一篇文章。

笔记:这类似于 这个帖子这个 但我不想阻止重定向,我只想保留 POST 数据。

这是我的 HTTPRedirectHandler 不起作用

class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
    """Return a Request or None in response to a redirect.

    This is called by the http_error_30x methods when a
    redirection response is received.  If a redirection should
    take place, return a new Request to allow http_error_30x to
    perform the redirect.  Otherwise, raise HTTPError if no-one
    else should try to handle this url.  Return None if you can't
    but another Handler might.
    """
    m = req.get_method()
    if (code in (301, 302, 303, 307) and m in ("GET", "HEAD")
        or code in (301, 302, 303) and m == "POST"):
        # Strictly (according to RFC 2616), 301 or 302 in response
        # to a POST MUST NOT cause a redirection without confirmation
        # from the user (of urllib2, in this case).  In practice,
        # essentially all clients do redirect in this case, so we
        # do the same.
        # be conciliant with URIs containing a space
        newurl = newurl.replace(' ', '%20')
        return Request(newurl,
                       headers=req.headers,
                       data=req.get_data(),
                       origin_req_host=req.get_origin_req_host(),
                       unverifiable=True)
    else:
        raise HTTPError(req.get_full_url(), code, msg, headers, fp)
有帮助吗?

解决方案

这实际上是一个非常糟糕的事情,我越想过这个问题。举例来说,如果我提交表单 http://example.com/add (用POST数据添加项) 并且所述响应是302重定向到 http://example.com/add 和予后的相同的数据,我贴在第一时间,我会在一个无限循环结束。不知道为什么我以前没有想到这一点。我将离开这里的问题只是作为一个警告,任何人想这样做。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top