Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending http headers with python

I've set up a little script that should feed a client with html.

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 shown as plain text in the browser. Can you please tell what I need to do ? I just can't find something in google that helps me..

Thanks.

like image 581
Niklas R Avatar asked Nov 29 '11 17:11

Niklas R


1 Answers

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

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

Also, to make the test more visible, put some content in the page:

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

After the response is sent, close the connection with:

client.close()

and

sock.close()

As the other posters have noted, terminate each line with \r\n instead of \n.

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

Here's all the 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()
like image 196
Raymond Hettinger Avatar answered Nov 15 '22 13:11

Raymond Hettinger