如何用标头和body构建Python帖子请求



我是Python的新手。我需要使用标题和身体详细信息向网站发布身份验证请求。我已经在下面发布了我到目前为止的代码。运行它时,我会在此行上获得语法错误:

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'
              }
        )

现在您可以按照往常来解析response

最新更新