TypeError:无法将str连接到HTTPSConnection中的字节

2024-06-06 19:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图提出授权请求,并提出了TypeError: can't concat str to bytes。我在网上搜索过,发现了类似的问题,但没有一个能帮助我解决问题。我目前在Jupyter工作(如果有帮助的话?),我也是一个python noob,所以请温柔一点

这是我的密码:

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'

我错过了什么?我不明白什么


Tags: inselfclienthttpurlbaserequesttype
2条回答
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\u info”,或者很可能是您将其定义为“request\u body”,而不记得了

固定这条线就足够了:

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

而不是命名字典request_body

我认为这个错误是由于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是一个dict对象。因此,转换为JSON可能会解决这个问题

import json

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

相关问题 更多 >