python - 试图从 API 获取 json 数据,得到 TypeError
问题描述
TypeError: POST 数据应该是字节、可迭代的字节或文件对象。它不能是 str 类型。
import json
import urllib.request as req
from urllib.parse import urlencode
url = "https://apiurl.example/search/"
payload = {"SearchString":"mysearch"}
response = req.urlopen(url, urlencode(payload))
data = response.read()
print(data.decode("utf-8"))
我究竟做错了什么?我在 API 的在线界面中尝试过的 url 或“有效负载”没有任何问题。在添加 urlencode 和 utf-8 解码之前,我收到一条错误消息:“TypeError: can't concat str to bytes”。在某些时候它返回了一个空列表,但不记得我当时做了什么。无论如何,它应该返回一些如上所述的数据。谢谢你的时间。
解决方案
我从来没有那样使用过请求。这是我如何完成它的示例,检查结果代码并在成功时解码 JSON:
import json
import requests
action_url = "https://apiurl.example/search/"
# Prepare the headers
header_dict = {}
header_dict['Content-Type'] = 'application/json'
# make the URL request
result = requests.get(action_url, headers=header_dict)
status_code = result.status_code
if (status_code == requests.codes.ok):
records = json.loads(result.content)
print 'Success. Records:'
print records
else:
print 'ERROR. Status: {0}'.format(status_code)
print 'headers: {0}'.format(header_dict)
print 'action_url: {0}'.format(action_url)
# Show the error messages.
print result.text
推荐阅读
- swift - 尝试在另一个数组中使用可解码结构时出现可解码错误
- c# - 为什么成功的 DBCC CHECKIDENT 会抛出 SqlException
- angular - Angular 5 - 如何为从数组列表创建的选择维护 ngmodel 数组
- c - UDP:每 x 秒从客户端读取一个新帧
- postgresql - JSQL Parser - 有关解析函数的信息
- c# - 如何在 .Net 1.1 中获取用户控件 HorizontalScroll 或 VerticalScroll 值
- php - 在 symfony2.8 中更新了用户和会话
- css - 如何在 Angular 2 / Ionic 2 中调整实时评论 div 的大小
- javascript - 如何通过ajax将数据数组发送到后端(php)
- android - 片段和列表视图子项