使用python发送HTTP标头

编程入门 行业动态 更新时间:2024-10-27 04:35:37
本文介绍了使用python发送HTTP标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经建立了一个小脚本,该脚本应该为html提供客户端.

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

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

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..

谢谢.

推荐答案

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

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

sock.close()

正如其他张贴者所指出的那样,以 \ r \ n 而不是 \ n 结束每一行.

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

通过这些添加,我可以运行成功的测试.在浏览器中,我输入了 localhost:8080 .

Will those additions, I was able to run successful test. In the browser, I entered 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()

更多推荐

使用python发送HTTP标头

本文发布于:2023-10-11 04:38:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1480706.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:python   HTTP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!