Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用头和体构造python post请求_Python_Json_Python 3.x - Fatal编程技术网

如何用头和体构造python post请求

如何用头和体构造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

我对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'
              }
        )
现在,您可以像往常一样解析得到的
响应