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

标签 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(url, data=json.dumps(data), headers=headers)
print response.status_code
print response.text

以上代码输出:

200
{"a":""}

但实际上,键“a”有一些我没有得到的值。我不明白它给我的状态代码为 200 即 OK 那么为什么我无法获得正确的 JSON 响应。我是否遗漏了代码中的某些内容?

最佳答案

您应该使用json=data在请求中传递json,但不要手动修改 header ,如果您这样做,您应该使用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()

关于python - 如何在 python 中发送 POST 请求并获得正确的 json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46640140/

相关文章:

python - 如何在 mpld3 上使用交互式图例插件显示标签?

javascript - node.js/express 在不从当前页面重定向的情况下发出发布请求

json - Swift:以 JSON 对象为主体的 Alamofire POST 请求

Python 请求包 : Handling xml response

python - 更改请求中的 url (Python)

python - C++ 中的通用异常处理

python - 针对数组内的 .NET 数组的嵌套列表理解

python - 如何使用python打印随机森林回归中重要特征的顺序?

javascript - var 检查 = $ ("input[no]").is (":checked")?2 :1; and how to reach 2nd database row

python 请求后查询失败 :cookies?