昨天遇到了一个奇怪的问题,在Python中需要传递dict参数,利用json.dumps将dict转为json格式用post方法发起请求:
params = {\"score\":{\"gt\":\"80\", \"lt\":\"90\"}} request.post(url, json.dumps(params))
但是在服务端接收到的参数日志为:
Parameters: {\"sno\"=>\"lt\"}
之前用Ruby的RestClient的gem包传递参数还是正常的:
params = {\"score\":{\"gt\":\"80\", \"lt\":\"90\"}} RestClient.post(url, params.to_json, :content_type => :json)
服务端接收到的参数日志正确,为:
Parameters: {\"score\"=>{\"gt\"=>\"80\", \"lt\"=>\"90\"}}
仔细观察后发现RestClient中第三个参数为header
百度之后发现应该在Python的request中添加header参数,指明所传的params格式为json,如下:
requests.post(url, data=json.dumps(params), headers={\'Content-Type\': \'application/json\'})
就可以正常在服务端得到传过来的参数了。
© 版权声明
THE END
暂无评论内容