如何在python中发送POST请求并获得正确的json响应?
问题描述:
我想在python中获得POST Web服务数据。为此,我试过如下:如何在python中发送POST请求并获得正确的json响应?
import requests
import json
headers = {'content-type': 'application/json','charset': 'utf-8'}
url = 'https://a.b.c.com/count/WebService.asmx/ReadJSON'
data = {'tick': '123456A123456B'}
response = requests.post(url, data=json.dumps(data), headers=headers)
print response.status_code
print response.text
以上代码的输出:
200
{"a":""}
但实际上,键 “一” 有一定的价值这我没有收到。我不明白它给我的状态代码为200,即OK,那么为什么我无法获得正确的JSON响应。我在代码中遗漏了什么吗?
答
您应该使用json=data
在请求中传递json,但不能手动修改标头,并且如果确定它是肯定的,您应该使用response.json()
来获取json结果。
import requests
headers = {'charset': 'utf-8'}
url = 'https://a.b.c.com/count/WebService.asmx/ReadJSON'
data = {'tick': '123456A123456B'}
response = requests.post(url, json=data, headers=headers)
print response.status_code
print response.json()
使用'response.json()',而不是'response.text',你不需要转储字典字符串,可以把它当作是 –
如果我过去了,响应= requests.post (url,data = data,headers = headers)我得到{u'StackTrace':u'',u'Message':u'There处理请求时出错。',u'ExceptionType':u'' }错误。 – kit