python post请求_python发送http的post请求

第一种方式:安装第三方库,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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值