繁体   English   中英

使用python发送http标头

[英]Sending http headers with python

我已经设置了一个小脚本,应该用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")

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

谢谢。

响应头应包含指示成功的响应代码。 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()

webob也会为您提供脏http详细信息

from webob import Response
....

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM