2017-07-31 68 views
0

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

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') 

但他们都没有工作。

请帮助我们吗?

感谢

+0

有没有一个'r.text'或'r.body'属性? 'dir(r)'的输出是什么? – RSHAP

+0

Hi @RSHAP no r.text or r.body attributes。 DIR(r)的输出是 [ 'CONTENT_DECODERS', 'REDIRECT_STATUSES', '__abstractmethods__', '__class__', '__del__', '__delattr__', '__dict__', '__DIR__', ' __doc__ ' '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', ' __init_subclass__', '__iter__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', [...] – Gusepo

回答

2

尝试请求模块

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) 
2

Python docs(重点煤矿):

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

类,其实例成功连接后,将返回。 未由用户直接实例化。

并且:推荐用于更高级别的HTTP客户端接口

又见请求包。

所以你可能会更好地使用requests直接。

在提出您的要求后,请使用json.loads(r.text)

0

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