Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I tried this , this, but didn't helped me much, getting same error still any idea whats causing the issue in below code.

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

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

Python version: 3.4

I thought issue should be solved long back as reported in Python 3.2 here

like image 586
pkm Avatar asked Feb 09 '23 23:02

pkm


1 Answers

urllib.request does not support passing in unencoded dictionaries; if you are sending JSON data you need to encode that dictionary to JSON yourself:

import json

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

You may want to look at installing the requests library; it supports encoding JSON for request bodies out-of-the-box by using the json keyword argument:

import requests

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

Note that the Content-Type header is set for you automatically.

like image 127
Martijn Pieters Avatar answered Feb 24 '23 08:02

Martijn Pieters