TypeError: can't concat str to bytes in HTTPSConnection

TypeError: can't concat str to bytes in HTTPSConnection

我正在尝试提出授权请求并提出 TypeError: can't concat str to bytes。我在网上搜索并发现了类似的问题,但其中 none 帮助解决了我的问题。我目前在 Jupyter 工作(如果这有帮助?)我也是一个 python 菜鸟,所以请保持温柔...

这是我的代码:

import http.client as httplib
import urllib.request, urllib.parse, urllib.error, base64
import requests as rq

base_url = 'api/url'
end_point = '/endpoint'
full_url = base_url + end_point

request_body = {
    'UserName':'un',
    'Password':'pw'
}

header = {
    'tenant': 'tenant name'  #required by vendor
}

print(type(base_url))
print(type(end_point))
print(type(full_url))
print(type(request_body))
print(type(header))

try:
    conn = httplib.HTTPSConnection(base_url)
    conn.request(method='POST',url=full_url, body=request_body, headers=header)
    response = conn.getresponse()
    data = response.read()
    print(type(data))
    print(data)
    conn.close()
except Exception as e:
    print("[Errno {0}] {1}".format(e.errno, e.strerror))

我收到以下错误:

TypeError: can't concat str to bytes

完整追溯:

<class 'str'>
<class 'str'>
<class 'str'>
<class 'dict'>
<class 'dict'>
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-1a19e8736fec> in <module>
     24     conn = httplib.HTTPSConnection(base_url)
---> 25     conn.request(method='POST',url=full_url, body=request_body, headers=header)
     26     response = conn.getresponse()

~\Documents\Anaconda\lib\http\client.py in request(self, method, url, body, headers, encode_chunked)
   1243         """Send a complete request to the server."""
-> 1244         self._send_request(method, url, body, headers, encode_chunked)
   1245 

~\Documents\Anaconda\lib\http\client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1289             body = _encode(body, 'body')
-> 1290         self.endheaders(body, encode_chunked=encode_chunked)
   1291 

~\Documents\Anaconda\lib\http\client.py in endheaders(self, message_body, encode_chunked)
   1238             raise CannotSendHeader()
-> 1239         self._send_output(message_body, encode_chunked=encode_chunked)
   1240 

~\Documents\Anaconda\lib\http\client.py in _send_output(self, message_body, encode_chunked)
   1063                     chunk = f'{len(chunk):X}\r\n'.encode('ascii') + chunk \
-> 1064                         + b'\r\n'
   1065                 self.send(chunk)

TypeError: can't concat str to bytes

During handling of the above exception, another exception occurred:

AttributeError                            Traceback (most recent call last)
<ipython-input-24-1a19e8736fec> in <module>
     30     conn.close()
     31 except Exception as e:
---> 32     print("[Errno {0}] {1}".format(e.errno, e.strerror))

AttributeError: 'TypeError' object has no attribute 'errno'

我在这里错过了什么?我不明白什么?

我认为这个错误是因为 request 方法中的 body=request_body

conn.request(method='POST',url=full_url, body=request_body, headers=header)

来自documentation

body may be a str, a bytes-like object, an open file object, or an iterable of bytes.

但在这种情况下 request_body 是一个字典对象。所以转换为 JSON 可能会解决这个问题。

import json

conn.request(method='POST',url=full_url, body=json.dumps(request_body), headers=header)
NameError                                 Traceback (most recent call last)
<ipython-input-3-75a4126e3e42> in <module>
     19 print(type(end_point))
     20 print(type(full_url))
---> 21 print(type(body_info))
     22 print(type(header))
     23 

NameError: name 'body_info' is not defined

您忘记定义 'body_info' 或者,很可能您将其定义为 'request_body' 但不记得了。

修复这一行就足够了:

body_info = {
    'UserName':'un',
    'Password':'pw'
}

而不是命名字典 request_body