如何在python中发送POST请求并获得正确的json响应?

如何在python中发送POST请求并获得正确的json响应?,python,post,python-requests,Python,Post,Python Requests,我想用python获取POST Web服务数据。为此,我尝试了以下方法: 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(ur

我想用python获取POST Web服务数据。为此,我尝试了以下方法:

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":""}

但是实际上,键“a”有一些我没有得到的值。我不明白它给我的状态代码是200,也就是说,好吧,那么为什么我不能得到正确的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
,您不需要将字典转储为字符串,您可以将其作为isIf传递,response=requests.post(url,data=data,headers=headers)传递,我得到{u'StackTrace':u',u'Message:u'处理请求时出错',u'ExceptionType':u'}错误。@Sraw-请参阅上面的注释。我试过你的解决办法,但对我无效。我得到的输出与回答中所示的相同。@kit您确定使用的是
json=data
,而不是
data=data
?@Sraw-是。我只使用json=数据。我将其从data=data改为json=data。@您可以打印出
response.request.headers
来比较两种不同的实现。此外,如果由于某些奇怪的原因,它确实对您不起作用,您可以更改为使用
response.json()
,以获得json结果。@Sraw-我将获得response.request.header作为{'Content-Length':'47','Accept-Encoding':'gzip,deflate','Accept':'/','User-Agent':'python-requests/2.18.4','Connection':'keep-alive','Content-Type':'application/json'},我使用respose.json()只查看数据。