python 中的 POST 数据有没有办法修复这个错误?

Is there any way to repair this error with POST data in python?

我需要检查 GPS 设备通信协议与日志服务器的兼容性。该应用程序允许您执行测试,将发送的帧与其支持的协议进行比较,并检查是否可以通过已支持的协议读取该帧。为此,我想使用共享测试,但出现错误。 https://github.com/traccar/traccar/blob/master/tools/test-integration.py

```
import sys
import os
import xml.etree.ElementTree
import urllib
import urllib.parse
import urllib.request as urllib2
import json
import socket
import time

messages = {
    'gps103' : 'imei:123456789012345,help me,1201011201,,F,120100.000,A,6000.0000,N,13000.0000,E,0.00,;'
}

baseUrl = 'http://172.16.43.210:8082'
user = { 'email' : 'admin', 'password' : 'admin' }

debug = '-v' in sys.argv

def load_ports():
    ports = {}
    dir = os.path.dirname(os.path.abspath(__file__))
    root = xml.etree.ElementTree.parse(dir + '\default.xml').getroot()
    for entry in root.findall('entry'):
        key = entry.attrib['key']
        if key.endswith('.port'):
            ports[key[:-5]] = int(entry.text)
    if debug:
        print('\nports: %s\n' % repr(ports))
    return ports

def login():
    request = urllib2.Request(baseUrl + '/api/session')
    response = urllib2.urlopen(request, urllib.parse.urlencode(user))
    if debug:
        print('\nlogin: %s\n' % repr(json.load(response)))
    return response.headers.get('Set-Cookie')

def remove_devices(cookie):
    request = urllib2.Request(baseUrl + '/api/devices')
    request.add_header('Cookie', cookie)
    response = urllib2.urlopen(request)
    data = json.load(response)
    if debug:
        print ('\ndevices: %s\n' % repr(data))
    for device in data:
        request = urllib2.Request(baseUrl + '/api/devices/' + str(device['id']))
        request.add_header('Cookie', cookie)
        request.get_method = lambda: 'DELETE'
        response = urllib2.urlopen(request)

def add_device(cookie, unique_id):
    request = urllib2.Request(baseUrl + '/api/devices')
    request.add_header('Cookie', cookie)
    request.add_header('Content-Type', 'application/json')
    device = { 'name' : unique_id, 'uniqueId' : unique_id }
    response = urllib2.urlopen(request, json.dumps(device))
    data = json.load(response)
    return data['id']

def send_message(port, message):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', port))
    s.send(message)
    s.close()

def get_protocols(cookie, device_id):
    params = { 'deviceId' : device_id, 'from' : '2000-01-01T00:00:00.000Z', 'to' : '2050-01-01T00:00:00.000Z' }
    request = urllib2.Request(baseUrl + '/api/positions?' + urllib.urlencode(params))
    request.add_header('Cookie', cookie)
    request.add_header('Content-Type', 'application/json')
    request.add_header('Accept', 'application/json')
    response = urllib2.urlopen(request)
    protocols = []
    for position in json.load(response):
        protocols.append(position['protocol'])
    return protocols

ports = load_ports()

cookie = login()
remove_devices(cookie)

devices = {
    '123456789012345' : add_device(cookie, '123456789012345'),
    '123456789012' : add_device(cookie, '123456789012'),
    '1234567890' : add_device(cookie, '1234567890'),
    '123456' : add_device(cookie, '123456'),
    '1234' : add_device(cookie, '1234')
}


all = set(ports.keys())
protocols = set(messages.keys())

print ('Total: %d' % len(all))
print ('Missing: %d' % len(all - protocols))
print ('Covered: %d' % len(protocols))

#if all - protocols:
#    print '\nMissing: %s\n' % repr(list((all - protocols)))

for protocol in messages:
    send_message(ports[protocol], messages[protocol])

time.sleep(10)

for device in devices:
    protocols -= set(get_protocols(cookie, devices[device]))

print ('Success: %d' % (len(messages) - len(protocols)))
print ('Failed: %d' % len(protocols))

if protocols:
    print ('\nFailed: %s' % repr(list(protocols)))

```

我收到了这个错误:

      File "C:\Users\ISUIT\Desktop\Ew.Prac\tt.py", line 159, in <module>
        cookie = login()
      File "C:\Users\ISUIT\Desktop\Ew.Prac\tt.py", line 112, in login
        response = urllib2.urlopen(request, urllib.parse.urlencode(user))
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 214, in urlopen
        return opener.open(url, data, timeout)
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 514, in open
        req = meth(req)
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1776.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 1277, in do_request_
        raise TypeError(msg)
    TypeError: POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.

我尝试使用 bytes(string, 'utf-8') 但它不起作用

使用 string.encode('utf-8') 将类型转换为 bytes