2017-07-11 30 views
1

我想從Python 3.6中使用urllib從API拉一些JSON數據。它需要傳遞頭部信息以進行授權。這裏是我的代碼:Python 3.6 urllib TypeError:不能連接字節到字符

import urllib.request, json 

headers = {"authorization" : "Bearer {authorization_token}"} 

with urllib.request.urlopen("{api_url}", data=headers) as url: 
    data = json.loads(url.read().decode()) 
    print(data) 

和錯誤消息我得到:

Traceback (most recent call last): 
    File "getter.py", line 5, in <module> 
with urllib.request.urlopen("{url}", data=headers) as url: 
    File "AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 223, in urlopen 
return opener.open(url, data, timeout) 
    File "AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 526, in open 
response = self._open(req, data) 
    File "AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 544, in _open 
'_open', req) 
    File "AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 504, in _call_chain 
result = func(*args) 
    File "AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 1361, in https_open 
context=self._context, check_hostname=self._check_hostname) 
    File "AppData\Local\Programs\Python\Python36-32\lib\urllib\request.py", line 1318, in do_open 
encode_chunked=req.has_header('Transfer-encoding')) 
    File "AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1239, in request 
self._send_request(method, url, body, headers, encode_chunked) 
    File "AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1285, in _send_request 
self.endheaders(body, encode_chunked=encode_chunked) 
    File "AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1234, in endheaders 
self._send_output(message_body, encode_chunked=encode_chunked) 
    File "AppData\Local\Programs\Python\Python36-32\lib\http\client.py", line 1064, in _send_output 
+ b'\r\n' 
TypeError: can't concat bytes to str 

Process finished with exit code 1 

不太清楚發生了什麼事情錯在這裏,我沒有任何輸入字節,所以我不知道爲什麼我m得到一個錯誤告訴我,我不能連接字節到str。

任何幫助,非常感謝!

+1

我認爲你應該使用'headers = headers' –

回答

2

data參數有望成爲類似字節的對象。你需要做到以下幾點:

urllib.request.urlopen({api_url}, data=bytes(json.dumps(headers), encoding="utf-8")) 
+0

工作感謝! –

+0

@MthetheWWinfield,我已經多次與這個問題作鬥爭。實際上,這行代碼是從我的一個項目中複製出來的。 –

相關問題