python - 使用 Python-Request 的 REST 发布

标签 python python-2.7 python-requests

为什么这个简单的代码没有将数据 POST 到我的服务:

import requests
import json

data = {"data" : "24.3"}
data_json = json.dumps(data)
response = requests.post(url, data=data_json)
print response.text

我的服务是这样使用 WCF 开发的:

  [OperationContract]
  [WebInvoke(Method = "POST", UriTemplate = "/test", ResponseFormat =    
      WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json)]
  string test(string data );

注意:如果删除输入参数 data 一切正常,可能是什么问题。

最佳答案

您需要设置内容类型标题:

data = {"data" : "24.3"}
data_json = json.dumps(data)
headers = {'Content-type': 'application/json'}

response = requests.post(url, data=data_json, headers=headers)

如果我将 url 设置为 http://httpbin.org/post,该服务器会向我回显发布的内容:

>>> import json
>>> import requests
>>> import pprint
>>> url = 'http://httpbin.org/post'
>>> data = {"data" : "24.3"}
>>> data_json = json.dumps(data)
>>> headers = {'Content-type': 'application/json'}
>>> response = requests.post(url, data=data_json, headers=headers)
>>> pprint.pprint(response.json())
{u'args': {},
 u'data': u'{"data": "24.3"}',
 u'files': {},
 u'form': {},
 u'headers': {u'Accept': u'*/*',
              u'Accept-Encoding': u'gzip, deflate, compress',
              u'Connection': u'keep-alive',
              u'Content-Length': u'16',
              u'Content-Type': u'application/json',
              u'Host': u'httpbin.org',
              u'User-Agent': u'python-requests/1.0.3 CPython/2.6.8 Darwin/11.4.2'},
 u'json': {u'data': u'24.3'},
 u'origin': u'109.247.40.35',
 u'url': u'http://httpbin.org/post'}
>>> pprint.pprint(response.json()['json'])
{u'data': u'24.3'}

如果您使用的是requests 2.4.2 或更新版本,您可以将 JSON 编码留给库;它也会自动为您设置正确的 Content-Type header 。将要作为 JSON 发送的数据传入 json 关键字参数:

data = {"data" : "24.3"}
response = requests.post(url, json=data)

关于python - 使用 Python-Request 的 REST 发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13941742/

相关文章:

python - python 内置的 open() 函数中的缓冲有什么用?

python - 为什么 render/requests-html 不抓取动态内容?

Python 2.7 类型错误 : __init__() takes exactly 4 arguments (1 given)

python - 使用Python从具有两列或三列数据的图像中使用OCR读取图像中的文本

python - 使用Python登录https网站

python-requests - 使用 Python 中的请求包通过 API key 调用 REST API

Python - 发送 HTTP GET 字符串 - 接收 301 永久移动 - 下一步是什么?

python - Panda python 文本文件处理成 xlsx

python - 我可以在 Google App Engine 中设置动态生成的 zip 文件内容的权限吗?

Python lambda函数计算数字的阶乘