Skip to main content
 首页 » 编程设计

python之如何用header和body构造python post请求

2025年02月15日7pander-it

我是 Python 的新手。 我需要使用 header 和正文详细信息向网站发布身份验证请求。 到目前为止,我已经在下面发布了代码。当我运行它时,我在这一行收到语法错误:

req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2') 

能否请您检查并让我知道哪里做错了?

import urllib.request 
import json 
 
body = {'identifier': 'my_id', 'password': 'my_encrypted_pwd', 'encryptedPassword': true} 
 
url = 'https://mywebsite.com/gateway/deal/session' 
req = urllib.request.Request(url) 
req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2') 
jsondata = json.dumps(body) 
jsondataasbytes = jsondata.encode('UTF-8') 
req.add_header('Content-Length', len(jsondataasbytes)) 
print (jsondataasbytes) 
response = urllib.request.urlopen(req, jsondataasbytes) 

请您参考如下方法:

我建议您应该使用 requests 模块,因为它比 urllib.request 更快、更好:

response = requests.put( 
        url, 
        body, headers={'API-KEY': 'my_api_key', 
                       'ACCOUNT-ID': 'my_account_id', 
                       'Content-Type': 'application/json; charset=UTF-8', 
                       'VERSION': '2' 
              } 
        ) 

现在您可以像往常一样解析您得到的响应。