如何用头和体构造python post请求
我对Python完全陌生。 我需要发布一个身份验证请求到一个网站使用头和身体的细节。 我已经在下面发布了到目前为止我已经发布的代码。当我运行它时,我在这一行得到语法错误:如何用头和体构造python post请求,python,json,python-3.x,Python,Json,Python 3.x,我对Python完全陌生。 我需要发布一个身份验证请求到一个网站使用头和身体的细节。 我已经在下面发布了到目前为止我已经发布的代码。当我运行它时,我在这一行得到语法错误: req.add_header('API-KEY': 'my_api_key', 'ACCOUNT-ID': 'my_account_id', 'Content-Type': 'application/json; charset=UTF-8', 'VERSION': '2') 你能回顾一下,让我知道我哪里出了错吗 import
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'
}
)
现在,您可以像往常一样解析得到的响应