python HTTP请求包

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import urllib2
import socket

def send(url,host,body=""):
	socket.setdefaulttimeout(2)
	request = urllib2.Request(url,body)
	request.add_header('User-Agent', 'Firefox')
	request.add_header('Cache-Control', 'no-cache')
	request.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
	request.add_header('Referer', "http://www.firefoxbug.com/")
	request.add_header('Keep-Alive',60)
	request.add_header('Connection', 'keep-alive')
	request.add_header('Host',host)
	try:
		response = urllib2.urlopen(request)
		code = response.code
		msg = response.msg
		print "status code %d"%code
		print "message : %s"%msg

		headers = response.headers
		print "\n\n%s"%headers

		data = response.read()
		print "data\n%s"%data
	except Exception,e:
		raise e

send("http://223.4.238.138","www.firefoxbug.net")

是否发送Post包可以通过Body字段是否为空来指定。

socket.setdefaulttimeout()来指定请求超时时间。

标签:Linux, Python, Http

评论已关闭