【问题标题】:From HTTPResponse to str in Python 3.6从 HTTPResponse 到 Python 3.6 中的字符串
【发布时间】:2018-01-07 06:23:24
【问题描述】:

从对 Vimeo API 的 POST 请求,我得到一个编码为 HTTPResponse 的 JSON 对象。

r = http.request('POST', 'https://api.vimeo.com/oauth/authorize/client?grant_type=client_credentials', headers={'Authorization': 'basic XXX'})

我没有找到将 HTTPResponse 转换为 str 或 Json 对象的方法。在stackoverflow中,我发现并尝试了以下选项:

json.loads(r.decode('utf-8'))

json.loads(r.readall().decode('utf-8'))

str(r, 'utf-8')

但它们都不起作用。

你能帮忙吗?

谢谢

【问题讨论】:

  • 没有r.textr.body 属性吗? dir(r)的输出是什么
  • 嗨@RSHAP 没有 r.text 或 r.body 属性。 dir(r) 的输出是 ['CONTENT_DECODERS', 'REDIRECT_STATUSES', 'abstractmethods', 'class', 'del', 'delattr', 'dict', 'dir', 'doc', 'enter', 'eq', '退出', '格式', 'ge', ' getattribute', 'gt', 'hash', 'init', 'init_subclass', 'iter', 'le', 'lt', '模块', 'ne', 'new', 'next', 'reduce', 'reduce_ex', 'repr', 'setattr', 'sizeof', 'str', '子类挂钩',[...]

标签: python json api vimeo


【解决方案1】:

使用可以使用 http.client 模块。示例:

import http.client
import json
conn = http.client.HTTPConnection('https://api.vimeo.com/oauth/authorize/client?grant_type=client_credentials')
headers = {'Authorization': 'basic XXX'}
params = varData
conn.request('POST', '', params, headers)
response = conn.getresponse()
content = bytes.decode(response.read(), 'utf-8') #return string value
res_map = json.loads(content) #if content is json string

欲了解更多信息,请参阅:http.client

【讨论】:

    【解决方案2】:

    来自Python docs(强调我的):

    class http.client.HTTPResponse(sock, debuglevel=0, method=None, url=None)

    连接成功后返回实例的类。 不是由用户直接实例化的。

    还有:

    另请参阅 Requests 包被推荐用于更高级别的 HTTP 客户端接口。

    所以你最好直接使用requests

    提出请求后,只需使用json.loads(r.text)

    【讨论】:

      【解决方案3】:

      尝试请求模块

      import requests
      import json 
      
      r=requests.post('https://api.vimeo.com/oauth/authorize/client?grant_type=client_credentials', varData,  headers={'Authorization': 'basic XXX'})
      response = json.loads(r.text)
      

      【讨论】:

        猜你喜欢
        • 2017-07-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        • 2021-03-25
        • 2016-06-15
        • 1970-01-01
        相关资源
        最近更新 更多