使用http请求传输二进制数据

时间:2019-03-22 13:50:38

标签: python http python-requests base64

我试图通过将文件分割成多个块,然后通过http get或post请求将它们发送到另一台服务器,在其中尝试将文件重新组合在一起,来传输jpg图像之类的文件。对于解码,我使用pythons base64模块。这是客户端应用程序:

import requests
import base64

URL = "http://10.0.2.5:8080/index.php"

export_file = open("C:\\Users\zarathustra\\Desktop\\cat.jpg", "rb")

while True:
    export_data = base64.urlsafe_b64encode(export_file.read(1024))
    if export_data:
        parameter = {"data" : export_data}
        r = requests.get(url = URL, params=parameter)
    else:
        print ("File transmitted.")
        break

这是接收数据的应用程序:

from http.server import BaseHTTPRequestHandler, HTTPServer
import base64

class my_Request_Handler(BaseHTTPRequestHandler):

    def _set_response(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def do_GET(self):

        output_file = open("/home/zarathustra/exfiltration.txt", "a")
        output_file.write(base64.urlsafe_b64decode(self.path[16:]))
        output_file.close()

        self._set_response()
        self.wfile.write("GET request for {}".format(self.path).encode('utf-8'))

我使用另一个脚本来重组数据:

import base64

file = open("/home/zarathustra/exfiltration.txt", "r")
data = file.read()
data2 = base64.b64decode(file.read())
file2 = open("/home/zarathustra/Katze.jpg", "wb")
file2.write(data2)

file.close()
file2.close()

接收方应用抛出以下错误:

Exception happened during processing of request from ('10.0.2.15', 51475)
Traceback (most recent call last):
  File "/usr/lib/python3.7/socketserver.py", line 316, in _handle_request_noblock
    self.process_request(request, client_address)
  File "/usr/lib/python3.7/socketserver.py", line 347, in process_request
    self.finish_request(request, client_address)
  File "/usr/lib/python3.7/socketserver.py", line 360, in finish_request
    self.RequestHandlerClass(request, client_address, self)
  File "/usr/lib/python3.7/socketserver.py", line 720, in __init__
    self.handle()
  File "/usr/lib/python3.7/http/server.py", line 426, in handle
    self.handle_one_request()
  File "/usr/lib/python3.7/http/server.py", line 414, in handle_one_request
    method()
    print(base64.urlsafe_b64decode(self.path[16:]))
  File "/usr/lib/python3.7/base64.py", line 133, in urlsafe_b64decode
    return b64decode(s)
  File "/usr/lib/python3.7/base64.py", line 87, in b64decode
    return binascii.a2b_base64(s)
binascii.Error: Incorrect padding

我使用stackoverflow研究了不正确的填充错误,并尝试了一些变体,但无法提出可行的解决方案。另外,我不确定我的拆分/解码和重新组装方法是否正确。有什么建议吗?

0 个答案:

没有答案