Sending http headers using python

I created a small script that should feed the html client.

import socket sock = socket.socket() sock.bind(('', 8080)) sock.listen(5) client, adress = sock.accept() print "Incoming:", adress print client.recv(1024) print client.send("Content-Type: text/html\n\n") client.send('<html><body></body></html>') print "Answering ..." print "Finished." import os os.system("pause") 

But it is displayed as plain text in the browser. Could you tell me what I need to do? I just can't find something on google that helps me.

Thanks.

+7
source share
2 answers

The response header should contain a response code indicating success. Before the Content-Type line, add:

 client.send('HTTP/1.0 200 OK\r\n') 

In addition, to make the test more visible, put some content on the page:

 client.send('<html><body><h1>Hello World</body></html>') 

After sending the response, close the connection with:

 client.close() 

and

 sock.close() 

As other posters noted, end each line \r\n instead of \n .

Will these additions, I was able to run a successful test. In the browser, I entered localhost:8080 .

Here is the whole code:

 import socket sock = socket.socket() sock.bind(('', 8080)) sock.listen(5) client, adress = sock.accept() print "Incoming:", adress print client.recv(1024) print client.send('HTTP/1.0 200 OK\r\n') client.send("Content-Type: text/html\r\n\r\n") client.send('<html><body><h1>Hello World</body></html>') client.close() print "Answering ..." print "Finished." sock.close() 
+13
source

webob also contains dirty http details for you

 from webob import Response .... client.send(str(Response("<html><body></body></html>"))) 
0
source

All Articles