python - Fiddler 请求到 Python Requests 请求

标签 python https httprequest python-requests fiddler

(我知道标题中有很多请求)
通过 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 Requests 请求。这是 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

最佳答案

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 文档。

关于python - Fiddler 请求到 Python Requests 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34994083/

相关文章:

python - 根据 Beautifulsoup 中的内容排除标签

python - Pandas:删除具有唯一索引值的数据帧行

javascript - 我正在尝试找到一种在服务器端使用 GPIO 输入将客户端重定向到另一个网页的方法 rpi, RPi.GPIO, python,flask,j s

.htaccess - 301 几个(但不是全部)http 到 https

docker - 如何让 SSL 与 .net core 和 Google Compute Engine 一起工作?

java - 将变量从 JSP 传递到 servlet

python - 如何确保使用 nosetests 调用 tearDown(在测试中未捕获异常的情况下)?

使用 Azure 网站和类似网站托管 iOS 企业应用程序

c# - Unity - WWW.text 在 Android 设备上返回 null

swift - api返回的数据总是nil?