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

标签 python json python-3.x

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

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

关于python - 如何用header和body构造python post请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46261478/

相关文章:

python - 用来自不同数据帧的数据有条件地填充 pandas 列

json - 从 JSON 字符串中删除反斜杠?

python - 类实例实现,初始化实例——来自SICP python

python - 从Python中的未知列表中删除负数

python-3.x - 类型错误 : can't pickle CompiledFFI objects

python - matplotlib选择图像的框区域然后放大

python - Wireshark 不显示带有 Python SSL 套接字的 SSL 数据包

python - 我怎样才能使这个 Python 递归函数返回一个平面列表?

MySQL条件过滤json数组中的元素

java - 在 spring restful webservice 中返回 JsonObject