【问题标题】:How to send POST Request in python and get proper json response?如何在 python 中发送 POST 请求并获得正确的 json 响应?
【发布时间】:2018-03-20 06:58:42
【问题描述】:

我想在 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":""}

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

【问题讨论】:

  • 使用response.json()而不是response.text,你不需要将你的字典转储为字符串,你可以按原样传递它
  • 如果我通过了,response = requests.post(url, data=data, headers=headers) 我得到 {u'StackTrace': u'', u'Message': u'There处理请求时出错。', u'ExceptionType': u''} 错误。

标签: python post python-requests


【解决方案1】:

你应该使用json=data在请求中传递json而不是手动修改headers,如果你确定是,你应该使用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()

【讨论】:

  • @Sraw- 请参阅上面的评论。我试过你的解决方案它对我不起作用。我得到的输出与答案中显示的相同。
  • @kit 你确定你使用的是json=data而不是data=data吗?
  • @Sraw- 是的。我只使用 json=data 。我将它从 data=data 更改为 json=data。
  • @kit 你可以打印出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() 仅用于查看数据。
猜你喜欢
  • 2012-09-13
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多