应为 class 'dict' 类型的可迭代数据指定 Content-Length

Content-Length should be specified for iterable data of type class 'dict'

我尝试了 this , this,但对我的帮助不大,得到同样的错误仍然不知道是什么导致了下面代码中的问题。

try:
    request = urllib.request.Request(url,data=payload,method='PUT',headers={'Content-Type': 'application/json'})
    response = urllib.request.urlopen(request)
except Exception as e:
    print(str(e))

出现错误:- 应为 class 'dict'

类型的可迭代数据指定 Content-Length

Python版本:3.4

我认为问题应该早就解决了,正如 Python 3.2 here

中所报告的那样

urllib.request不支持传入未编码的字典;如果您要发送 JSON 数据,您需要 编码 那个字典给 JSON 自己:

import json

json_data = json.dumps(payload).encode('utf8')
request = urllib.request.Request(url, data=json_data, method='PUT',
                                 headers={'Content-Type': 'application/json'})

您可能需要查看安装 requests library;它支持使用 json 关键字参数对请求主体 out-of-the-box 进行编码 JSON:

import requests

response = requests.put(url, json=payload)

请注意,Content-Type header 是自动为您设置的。