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,它要求我将 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 发送它。
EDIT:按照要求,这是我得到的错误。由于这是一个 Flask 应用程序,因此这是调试器的屏幕截图:
截屏 https://chitoge.quad.moe/storage/sharex/2015-12-22_15-10-13.png
Adding .encode('utf-8')
给我一个“预期的字符串或缓冲区”错误
EDIT 2: 截屏 https://chitoge.quad.moe/storage/sharex/2015-12-22_15-30-02.png调试器的.encode('utf-8')
added