urllib2 and json

后端 未结 6 732
北恋
北恋 2020-11-29 00:58

can anyone point out a tutorial that shows me how to do a POST request using urllib2 with the data being in JSON format?

6条回答
  •  野性不改
    2020-11-29 01:27

    Whatever urllib is using to figure out Content-Length seems to get confused by json, so you have to calculate that yourself.

    import json
    import urllib2
    data = json.dumps([1, 2, 3])
    clen = len(data)
    req = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Content-Length': clen})
    f = urllib2.urlopen(req)
    response = f.read()
    f.close()
    

    Took me for ever to figure this out, so I hope it helps someone else.

提交回复
热议问题