如何在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响应。我在代码中遗漏了什么吗?

+0

使用'response.json()',而不是'response.text',你不需要转储字典字符串,可以把它当作是 –

+0

如果我过去了,响应= requests.post (url,data = data,headers = headers)我得到{u'StackTrace':u'',u'Message':u'There处理请求时出错。',u'ExceptionType':u'' }错误。 – kit

您应该使用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() 
+0

@ Sraw-请参阅上面的评论。我试过你的解决方案,它不适合我。我得到的答案与答案中显示的相同。 – kit

+0

@kit你确定你正在使用'json = data'而不是'data = data'吗? – Sraw

+0

@ Sraw-是的。我只使用json =数据。我将其从data = data更改为json = data。 – kit