Python 3.6 urllib 类型错误:无法将字节串与字符串连接

21
我正在尝试使用Python 3.6中的urllib从API中提取一些JSON数据。它需要传递标头信息进行授权。以下是我的代码:
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

我不太确定这里出了什么问题,因为我没有输入任何字节,所以我不知道为什么会出现错误提示我不能将字节连接到字符串。


5
我认为你应该使用 headers=headers - t.m.adam
1个回答

27

参数 data 应该是类似字节的对象。您需要执行以下操作:

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

1
@MatthewWinfield,我曾经多次遇到过这个问题。实际上,这行代码是从我的一个项目中复制出来的。 - Nick Chapman
我的使用情况是一个API(WebinarJam)。虽然我没有收到任何Django/Python错误,但是认证使用POST数据(可能不是最好的想法,但我无法更改),失败了。另一方面,使用requests库,它可以工作(使用与POST数据相同的字典)。 - Jens-Erik Weber

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接