从 HTTPResponse 到 Python 3.6 中的 str

From HTTPResponse to str in Python 3.6

从对 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 对象的方法。在 Whosebug 中,我发现并尝试了以下选项:

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

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

str(r, 'utf-8')

但其中 none 有效。

你能帮忙吗?

谢谢

尝试请求模块

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)

来自 Python docs(强调我的):

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

Class whose instances are returned upon successful connection. Not instantiated directly by user.

还有:

See also The Requests package is recommended for a higher-level HTTP client interface.

所以你最好直接使用 requests

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

使用可以使用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