rocksteady的解决方案可行
他最初确实提到了字典。但以下代码使用requests发送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发送它。
编辑:根据要求,这里是我得到的错误。由于这是一个flask应用程序,因此以下是调试器的屏幕截图:
屏幕截图
添加.encode('utf-8')
会给我一个“预期字符串或缓冲区”的错误。
编辑2:带有.encode('utf-8')
的调试器的屏幕截图
.encode('utf-8')
调用。加上后还有错误吗? - Gary van der Merwe