【问题标题】:Trying to get json data from API, got TypeError试图从 API 获取 json 数据,得到 TypeError
【发布时间】:2018-06-04 16:37:53
【问题描述】:

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”。在某些时候它返回了一个空列表,但不记得我当时做了什么。无论如何,它应该返回一些如上所述的数据。谢谢你的时间。

【问题讨论】:

    标签: python json api


    【解决方案1】:

    我从来没有那样使用过请求。这是我如何完成它的示例,检查结果代码并在成功时解码 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
    

    【讨论】:

      【解决方案2】:

      我现在知道了。

      import urllib.request
      import urllib.parse
      
      
      url = "https://apiurl.example/search"
      search_input = input("Search ")
      payload = {"SearchString":search_input}
      
      params = urllib.parse.urlencode(payload)
      params = params.encode('utf-8')
      
      f = urllib.request.urlopen(url, params)
      output = f.read()
      
      print(output)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-22
        • 2015-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多