从HTTPResponse到python3.6中的str

2024-04-25 21:05:43 发布

您现在位置:Python中文网/ 问答频道 /正文

从对vimeoapi的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中,我找到并尝试了以下选项:

^{pr2}$

但没有一个奏效。在

你能帮忙吗?在

谢谢


Tags: 对象httpscomclientapijsonhttp编码
3条回答

来自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)。在

try with requests模块

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)

使用可以使用http.客户端模块。示例:

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

相关问题 更多 >