Python 3.6 urllib TypeError:无法将字节连接到 str [英] Python 3.6 urllib TypeError: can't concat bytes to str

查看:15
本文介绍了Python 3.6 urllib TypeError:无法将字节连接到 str的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Python 3.6 中的 urllib 从 API 中提取一些 JSON 数据.它需要传递标头信息以进行授权.这是我的代码:

I'm trying to pull some JSON data from an API using urllib in Python 3.6. It requires header information to be passed for authorization. Here is my code:

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

不太确定这里出了什么问题,我没有输入任何字节,所以我不确定为什么我收到一个错误,告诉我我不能将字节连接到 str.

Not too sure what's going wrong here, I'm not inputting any bytes so I'm not sure why I'm getting an error telling me I can't concat bytes to str.

推荐答案

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

The data argument is expected to be a bytes-like object. you need to do the following:

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

这篇关于Python 3.6 urllib TypeError:无法将字节连接到 str的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆