標籤:ram 串連符 == import xxx end str int gen
今天用python的socket類比了下post請求,通過這個執行個體可以更加瞭解python中socket的使用,以及http請求和socket的相互關係等知識.
#coding=utf-8import socket
if __name__=="__main__": s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("www.xxxxx.com",80))
#pyhon 字串很長時可以用下面這種括弧加雙引號的方式, 這樣也不用像PHP那樣 多行字串需要用串連符串連起來 。
str=("POST /login/log HTTP/1.1\r\n" "Host: www.xxxxx.com\r\n" "User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0\r\n" "Referer: http://www.xxxxx.com/\r\n" "Content-Length: 17\r\n" "Cookie: session=f28edeacd71e759d05a80bb3cd9c91856952b3e3%7E58eb987a9efb26-19897462\r\n" "Content-Type: application/x-www-form-urlencoded\r\n" "Connection: keep-alive\r\n\r\n" "param1=a¶m2=b" ) # post 的關鍵是頭部的 Content-Type: application/x-www-form-urlencoded\r\n 這行,之前唯寫了x-www-form-urlencoded,提交過去,後端php列印$_POST一直為空白
# Content-Length: 17\r\n 的17是內容裡要post的參數的長度(即param1=a¶m2=b),注意頭部和內容要用 \r\n\r\n 分開
s.send(str) data=s.recv(2084) print data
#伺服器一般發送完訊息後,經過確認會主動斷開socket s.close()
python用socket類比post請求