如何在 Python 2.7 中使用 `allow_redirects` 来解决“302 Found”状态

How to use `allow_redirects` in Python 2.7 in order to solve "302 Found" status

问题描述

我正在使用以下 python 代码,以便通过 API 从给定网站检索数据。问题是我没有收到任何东西。当我 print(str(response.status)+" "+response.reason) 时,我得到以下信息:302 FOUND 并且没有打印任何内容。据我所见The HTTP response status code 302 Found is a common way of performing URL redirection.

问题

我看到有一种方法可以将 allow_redirects 设置为 False 以解决该问题。我被迫使用python 2.7。我无法使用 python 3.0。有没有办法在python 2.7的请求中添加allow_redirects?我也不能使用 requests 库。我可以使用 import requests.


#!/usr/bin/env python
import sys
import json
import httplib

# Retrieve list of errors from Error Viewer
def retrieve_errors_from_error_viewer(errors):
    headers = {"Content-Type": "application/json","Accept": "text/html"}
    data = {"dba": "XXX", "phase": "PROD"}
    conn = httplib.HTTPConnection('errorviewer.toys.net')
    conn.request('POST', '/api/errors', json.dumps(data), headers)
    response = conn.getresponse()
    print(str(response.status)+"  "+response.reason)
    print(response.read())


if __name__ == "__main__":
    # Retrieve Errors From ErrorViewer
    errors = []
    retrieve_errors_from_error_viewer(errors)

如果您使用 httplib2 而不是 httplib,您可以使用 follow_all_redirects 选项来解决您的问题。