码迷,mamicode.com
首页 > 编程语言 > 详细

Python-requests之POST Data的json问题

时间:2016-07-25 12:55:12      阅读:1148      评论:0      收藏:0      [点我收藏+]

标签:

代码如下:

import json
import requests
r = requests.post(url, data = {"a": json.dumps({"b": "c"})}); #url为随意URL

使用Fiddler抓包,虽然在WebForms里面看到格式如下:

技术分享

但是在Raw中看到结果如下:

技术分享

即自动执行了urlencode,查看requests/models.py源码发现,如果数据可迭代,即自动加入"application/x-www-form-urlencoded"头,并且执行urlencode:

PreparedRequest类的prepare_body方法中

if data:
    body = self._encode_params(data)
    if isinstance(data, basestring) or hasattr(data, read):
        content_type = None
    else:
        content_type = application/x-www-form-urlencoded

RequestEncodingMixin类中_encode_params(data)方法中

if isinstance(data, (str, bytes)):
    return data
elif hasattr(data, read):
    return data
elif hasattr(data, __iter__):
    result = []
    for k, vs in to_key_val_list(data):
        if isinstance(vs, basestring) or not hasattr(vs, __iter__):
            vs = [vs]
        for v in vs:
            if v is not None:
                result.append(
                    (k.encode(utf-8) if isinstance(k, str) else k,
                     v.encode(utf-8) if isinstance(v, str) else v))
    return urlencode(result, doseq=True)
else:
    return data

解决办法:

import json
import requests

headers = {"Content-Type": "application/x-www-form-urlencoded"} 
data = "a=%s" %  json.dumps({"b": "c"})
r = requests.post(url, data = data, headers = headers);

 

Python-requests之POST Data的json问题

标签:

原文地址:http://www.cnblogs.com/JohnABC/p/5702998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!