使用python发送http标头

问题描述 投票:0回答:3

我已经设置了一个小脚本,应该向客户端提供 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")

但它在浏览器中显示为纯文本。你能告诉我我需要做什么吗?我只是在谷歌中找不到对我有帮助的东西..

谢谢。

python html sockets client
3个回答
18
投票

响应标头应包含指示成功的响应代码。 在 Content-Type 行之前添加:

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

另外,为了使测试更加明显,请在页面中放置一些内容:

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

发送响应后,关闭连接:

client.close()

sock.close()

正如其他发帖者所指出的,每行以

\r\n
而不是
\n
结束。

有了这些补充,我就能够成功运行测试了。在浏览器中,我输入了

localhost:8080

这是所有代码:

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()

0
投票

webob 还为您处理肮脏的 http 详细信息

from webob import Response
....

client.send(str(Response("<html><body></body></html>")))

0
投票

@Raymond's snippet的Python 3变体(适合查看浏览器的http请求标头)。

import socket sock = socket.socket() sock.bind(('', 8080)) # ('127.0.0.1', 8080) for localhost sock.listen(5) client, address = sock.accept() print('Incoming:', address) print(client.recv(1024)) print() encoding = 'ascii' client.send(bytes('HTTP/1.0 200 OK\r\n', encoding)) client.send(bytes('Content-Type: text/html\r\n\r\n', encoding)) client.send(bytes('<html><body><h1>Hello World</h1></body></html>', encoding)) client.close() print('Answering ...') print('Finished.') sock.close()
    
© www.soinside.com 2019 - 2024. All rights reserved.