Skip to main content
 首页 » 编程设计

python之Fiddler 请求到 Python Requests 请求

2024年10月24日11thcjp

(标题中有很多请求,我知道)
使用 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 文档。