标签:
代码如下:
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