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 <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)

原创文章,转载请注明: 转载自成长的企鹅

本文链接地址: python发送http的post请求

关于我:成长的企鹅简介

4 条评论

希望和大家多多交流,多多分享。和大家一起收获,一起成长。 目前从事知识图谱工作。

4 条评论

MosesTak

Good post, I enjoyed it a lot.I was pretty lucky to find your website. It has a lot of helpful information!

回复

MosesTak

Recently I’ve come across one article which I believe you can find helpful. Someone will take a steaming dump all over it, however it answered some of my questions.

回复

MosesTak

I have found loads of helpful info on your site this page in particular. Thank you for posting.

回复

MosesTak

Thank you for helping people find the information they need. Good stuff as usual. Keep up the great work!!!

回复

发表评论