2017-07-31 27 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