与Python HTTP Simple Server的HTTPS安全连接

时间:2019-04-22 17:05:08

标签: python http https

感谢您对我的最后一个问题的回答,我能够在Python Simple HTTP服务器上获得持久的http连接。我现在试图扩展它以使用安全的HTTP连接。我构建了自签名证书,并使用ssl.wrap_socket()函数将它们传递到http.server。其余代码与不安全连接相同(正常工作),但是我收到501错误,说不支持“ POST”。相同的客户端代码可与Apache安全连接。

错误:

  

127.0.0.1--[22 / Apr / 2019 16:54:24]代码501,消息不支持的方法('POST')

     

127.0.0.1--[22 / Apr / 2019 16:54:24]“ POST / HTTP / 1.1” 501-

服务器代码:

from http.server import HTTPServer, BaseHTTPRequestHandler
import ssl

from io import BytesIO
import time
import datetime
import logging

class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):


    def do_GET(self):
        self.send_response(200)
        self.send_header("Connection", "keep-alive")
        self.send_header("Content-Length", str(len('Hello, world!')))
        self.wfile.write(b'Hello, world!')

    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        body = self.rfile.read(content_length)
        print("Received POST: " + body.decode())

        curr_time = datetime.datetime.now()
        data = ('{"msgid":"0x0002", "timestamp": "'+ str(curr_time) +'", "message":"Test https response from Python HTTP server"}').encode()

        # Send the response
        self.send_response(200)
        self.send_header("Connection", "keep-alive")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()

        response = BytesIO()
        response.write(data)
        self.wfile.write(response.getvalue())

print("Simple HTTP Server running...")
logging.basicConfig(level=logging.DEBUG)

httpd = HTTPServer(('', 8000), BaseHTTPRequestHandler)

httpd.socket = ssl.wrap_socket (httpd.socket, 
        keyfile="/etc/ssl/private/http.key", 
        certfile='/etc/ssl/certs/http.crt', 
        server_side=True,
        ssl_version=ssl.PROTOCOL_TLSv1)

httpd.serve_forever()

0 个答案:

没有答案