簡體   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