【问题标题】:Content-Length should be specified for iterable data of type class 'dict'应为“dict”类型的可迭代数据指定 Content-Length
【发布时间】:2015-06-03 09:30:04
【问题描述】:

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

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

得到错误:- 应该为类型类 'dict' 的可迭代数据指定 Content-Length

Python 版本:3.4

我认为问题应该早在 Python 3.2 here 中报告的那样解决

【问题讨论】:

    标签: python python-3.4


    【解决方案1】:

    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 关键字参数为请求正文编码 JSON:

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

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

    【讨论】:

      猜你喜欢
      • 2022-07-18
      • 2017-11-12
      • 2022-01-23
      • 2019-07-12
      • 2017-08-26
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 2021-10-19
      相关资源
      最近更新 更多