【问题标题】:Fiddler request to a Python Requests requestFiddler 请求到 Python Requests 请求
【发布时间】:2016-01-25 13:41:09
【问题描述】:

(我知道标题中有很多请求)
有了 Fiddler,我得到了一个工作请求。它正是我想要的。当我尝试在 python 中重现它时,它不起作用。这是 Fiddler 请求:

POST https://ichthus.zportal.nl/api/v3/oauth/ HTTP/1.1
Host: ichthus.zportal.nl
Content-Type: application/x-www-form-urlencoded

username=138777&password=XXXXX&client_id=OAuthPage&redirect_uri=%2Fmain%2F&scope=&state=4E252A&response_type=code&tenant=ichthus

这是我尝试过的 Python 请求代码:

import requests
endpoint = "https://ichthus.zportal.nl/api/v3/oauth/"
authData = {
    'username': '138777',
    'password': 'XXXXX',
    'client_id': 'OAuthPage',
    'redirect_uri': '/main/',
    'scope': '',
    'state': '4E252A',
    'response_type': 'code',
    'tenant': 'ichthus',
}
header = {
    'Host': 'ichthus.zportal.nl',
    'Content-Type': 'application/x-www-form-urlencoded',
}

response = requests.post(endpoint, data=authData, headers=header)
print response.headers
print response.status_code

通过Request to Code,我设法将其发送到 python URLlib2 请求。但我以前从未使用过 URLlib,我想知道它是否可以转换为 Python 请求请求。这是 Python URLlib2 代码:

def make_requests():
    response = [None]
    responseText = None

    if(request_ichthus_zportal_nl(response)):
        responseText = read_response(response[0])

        response[0].close()

def request_ichthus_zportal_nl(response):
    response[0] = None

    try:
        req = urllib2.Request("https://ichthus.zportal.nl/api/v3/oauth/")

        req.add_header("Content-Type", "application/x-www-form-urlencoded")

        body = "username=138777&password=XXXX&client_id=OAuthPage&redirect_uri=%2Fmain%2F&scope=&state=4E252A&response_type=code&tenant=ichthus"

        response[0] = urllib2.urlopen(req, body)

    except urllib2.URLError, e:
        if not hasattr(e, "code"):
            return False
        response[0] = e
    except:
        return False

    return True

【问题讨论】:

    标签: python https httprequest python-requests fiddler


    【解决方案1】:

    Requests 是一个非常流行的外部库,但我不建议依赖它。

    我确实注意到您在请求中发送了以下“数据”

    authData = {
    'username': '138777',
    'password': 'XXXXX',
    'client_id': 'OAuthPage',
    'redirect_uri': '/main/',
    'scope': '',
    'state': '4E252A',
    'response_type': 'code',
    'tenant': 'ichthus',
    }
    

    但是您指定您的数据类型为'Content-Type': 'application/x-www-form-urlencoded',并且您从未对数据进行编码。这也可能是你的罪魁祸首。

    另外。 Requests 只是 urllib2 的一个包装器,它可以自动完成很多工作。

    尝试在 urllib/2 中使用它

    Urllib2.urlopen (url, data) 
    

    使用

    对数据进行 url 编码
    Urllib.urlencode ()
    

    有关更多详细信息,请参阅 python 文档。

    【讨论】:

      猜你喜欢
      • 2018-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多