python用socket模拟post请求,,今天用python的


今天用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&param2=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&param2=b),注意头部和内容要用 \r\n\r\n 分开  
    s.send(str)    data=s.recv(2084)    print data    
  #服务器一般发送完消息后,经过确认会主动断开socket s.close()

python用socket模拟post请求

评论关闭