python - 发送 JSON 字符串作为 post 请求

标签 python json http python-3.x

rocksteady 的解决方案奏效了

他最初确实指的是字典。但是以下发送 JSON 字符串的代码也使用请求产生了奇迹:

import requests

headers = {
  'Authorization': app_token
}
url = api_url + "/b2api/v1/b2_get_upload_url"
content = json.dumps({'bucketId': bucket_id})

r = requests.post(url, data = content, headers = headers)

我正在使用一个 API,该 API 要求我将 JSON 作为 POST 请求发送以获得结果。问题是 Python 3 不允许我这样做。

以下 Python 2 代码运行良好,实际上它是官方示例:

request = urllib2.Request(
    api_url +'/b2api/v1/b2_get_upload_url',
    json.dumps({ 'bucketId' : bucket_id }),
    headers = { 'Authorization': account_authorization_token }
)
response = urllib2.urlopen(request)

然而,在 Python 3 中使用这段代码只会让它提示数据无效:

import json
from urllib.request import Request, urlopen
from urllib.parse import urlencode

# -! Irrelevant code has been cut out !-

headers = {
  'Authorization': app_token
}
url = api_url + "/b2api/v1/b2_get_upload_url"

# Tested both with encode and without
content = json.dumps({'bucketId': bucket_id}).encode('utf-8')

request = Request(
  url=url,
  data=content,
  headers=headers
)

response = urlopen(req)

我试过做 urlencode(),就像你应该做的那样。但这会从 Web 服务器返回 400 状态代码,因为它需要纯 JSON。即使纯 JSON 数据无效,我也需要以某种方式强制 Python 发送它。

编辑:根据要求,这是我得到的错误。由于这是一个 flask 应用程序,这里是调试器的屏幕截图:

Screenshot

添加 .encode('utf-8') 给我一个“预期的字符串或缓冲区”错误

编辑 2:Screenshot添加了 .encode('utf-8') 的调试器

最佳答案

由于我有一个类似的应用程序正在运行,但客户端仍然丢失,所以我自己尝试了。 正在运行的服务器来自以下练习:

Miguel Grinberg - designing a restful API using Flask

这就是它使用身份验证的原因。

有趣的部分:使用requests,您可以保留字典原样。

看看这个:

username = 'miguel'
password = 'python'

import requests
content = {"title":"Read a book"}

request = requests.get("http://127.0.0.1:5000/api/v1.0/projects", auth=(username, password), params=content)
print request.text

它似乎有效:)

更新 1:

POST 请求使用 requests.post(...) 这在这里描述得很好:python requests

更新 2:

为了完成答案:

requests.post("http://127.0.0.1:5000/api/v1.0/projects", json=content)

发送 json 字符串。

json 是请求的有效参数,内部使用 json.dumps()...

关于python - 发送 JSON 字符串作为 post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34417279/

相关文章:

python - 如何将其存储在 python 图形的邻接列表中?

c# - 如何使 Json.NET 成为默认的 Json 序列化程序

java - Jackson 还需要 getter 方法来使用 @JsonCreator 正确序列化 bean 属性

html - 将特定于选项卡的数据绑定(bind)到 HTTP GET 请求

python - 创建具有线性渐变的图像 mask

python - 无法让 pythonXY 在我的笔记本电脑上运行

用于操作 LED 的 Python 按位逻辑

jquery - 如何在jqplot中渲染json数据

http - 如何在 Delphi 中使用 HTTP 客户端 API

php - 隐藏标题发布数据