第一种方式:安装第三方库,pycurl:
import pycurl
import StringIO
import urllib
def PostData(query):
url = "http://test.xinghaixu.com/query"
params = [{'test1':'test1','test2':'test2']
post_data_dic ={"method":"CommonQueryService", "params":params}
crl = pycurl.Curl()
crl.setopt(pycurl.VERBOSE,1)
crl.setopt(pycurl.FOLLOWLOCATION, 1)
crl.setopt(pycurl.MAXREDIRS, 5)
#crl.setopt(pycurl.AUTOREFERER,1)
crl.setopt(pycurl.USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322)")
crl.setopt(pycurl.CONNECTTIMEOUT, 60)
crl.setopt(pycurl.TIMEOUT, 300)
#crl.setopt(pycurl.PROXY,proxy)
crl.setopt(pycurl.HTTPPROXYTUNNEL,1)
#crl.setopt(pycurl.NOSIGNAL, 1)
crl.fp = StringIO.StringIO()
# Option -d/--data HTTP POST data
crl.setopt(crl.POSTFIELDS, json.dumps(post_data_dic, ensure_ascii=False))
crl.setopt(pycurl.URL, url)
crl.setopt(crl.WRITEFUNCTION, crl.fp.write)
crl.perform()
return crl.fp.getvalue()
第二种方式:python自带的urllib库
import urllib
import urllib2
def PostData(query):
url = 'http://test.xinghaixu.com/query'
params = [{'test1':'test1','test2':'test2'}]
postDict = {}
postDict["method"] = "CommonQueryService"
postDict["params"] = params
#postData = urllib.urlencode(postDict);
postData = json.dumps(postDict, ensure_ascii=False)
req = urllib2.Request(url, postData);
# in most case, for do POST request, the content-type, is application/x-www-form-urlencoded
req.add_header('Content-Type', "application/x-www-form-urlencoded");
resp = urllib2.urlopen(req);
the_page = resp.read()
return the_page
PS:python在发送post的参数的时候,需要关注服务器端是支持post数组的方式还是post字符串的方式:
(1)发送数组:
postData = json.dumps(postDict, ensure_ascii=False)
(2)发送a=AAA&b=BBB 这种类似的参数形式:
postData = urllib.urlencode(postDict)