最近在使用python做接口调用同步数据,发现python中http请求方法有很多种,现汇总如下:

1. python自带库 —— urllib2

python自带库urllib2使用的比较多,简单使用如下:

get请求

    import urllib2
    response = urllib2.urlopen('http://localhost:8080/api')
    print response.read()

post请求

    import urllib2
    import urllib
    post_data = urllib.urlencode({})
    response = urllib2.urlopen('http://localhost:8080/, post_data)
    print response.read()
    print response.getheaders()

2. python自带库 —— httplib

httplib是一个相对底层的http请求模块,urlib就是基于httplib封装的。

get请求

    import httplib
    conn = httplib.HTTPConnection("www.python.org")
    conn.request("GET", "/index.html")
    r1 = conn.getresponse()
    print r1.status, r1.reason
    data1 = r1.read()
    conn.request("GET", "/parrot.spam")
    r2 = conn.getresponse()
    data2 = r2.read()
    conn.close()

post请求

    import httplib, urllib
    params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
    headers = {"Content-type": "application/x-www-form-urlencoded",  "Accept": "text/plain"}
    
    conn = httplib.HTTPConnection("bugs.python.org")
    conn.request("POST", "", params, headers)
    response = conn.getresponse()
    data = response.read()
    print data
    conn.close()

3. 第三方库 —— requests

推荐使用,发送get/post请求超级简单、功能丰富,最重要的是自带json解析!

get请求

    print requests.get('http://localhost:8080).text

post请求

    payload = {'key1': 'value1', 'key2': 'value2'}
    r = requests.post("http://httpbin.org/post", data=payload)
    print r.text

需要认证的post请求

    url = 'http://localhost:8080'
    r = requests.post(url, data={}, auth=HTTPBasicAuth('admin', 'admin'))
    print r.status_code
    print r.headers
    print r.reason