Search code examples
pythonhtmlhttpserversimplehttprequesthandler

Browser doesn't get response header from my inherited http.server.SimpleHTTPRequestHandler


I am trying to build a HTTP server by inheriting http.server.SimpleHTTPRequestHandler.

It works fine and unless that the browser just doesn't know my server is trying to send HTML data, and keep rendering the response HTML in plain text.

However, I have already set self.send_header('Content-Type', 'text/html; charset=UTF-8') in my server.

By check, I found that my browser seems not getting any response header from my server at all, though the response content is received.

It is very weird. Why is that?

I want to let the browser get the reponse header, so that the HTML response can be rendered as HTML instead of as plain text, what should I do?

Here is an example for test, by removing unrelated part from my server code:

import http.server
import socketserver

class CustomHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        html_content = "<html><body><h1>Hello, World!</h1></body></html>"
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=UTF-8')
        self.send_header('Content-Length', len(html_content))
        self.wfile.write(html_content.encode('utf-8'))
            
def main(port_no):
    with socketserver.TCPServer(("", port_no), CustomHandler) as httpd:
        print("Serving at port ", port_no)
        httpd.serve_forever()

if __name__ == '__main__':
    main(8098)

Solution

  • You have to add the URL for the server:

    import http.server
    import socketserver
    
    class CustomHandler(http.server.SimpleHTTPRequestHandler):
      def do_GET(self):
        html_content = "<html><body><h1>Hello, World!</h1></body></html>"
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=UTF-8')
        self.send_header('Content-Length', str(len(html_content)))
        self.end_headers()
        self.wfile.write(html_content.encode('utf-8'))
    
    def main(port_no):
       with socketserver.TCPServer(("127.0.0.1", port_no), CustomHandler) as httpd:
         print("Serving at port", port_no)
         httpd.serve_forever()
    
    if __name__ == '__main__':
      main(8098)