试用httplib

python的httplib是个很简单的模块,看手册也没有几个方法。我平时使用就更简单了,发送一个get请求,得到response,然后就没了。话不多说,下面直接贴出来我常用的两个操作get和post,如下:

代码

check_http.py

#!/usr/bin/env python
#coding: utf-8

import httplib
import urllib

def get_http(host,uri,method="GET"):
    try:
        conn = httplib.HTTPConnection(host)
        conn.request(method,uri)
        r = conn.getresponse()
        data = r.read()
        status = r.status
    except httplib.HTTPException as e:
        print "Error: %s" % e
    finally:
        conn.close()
    print "Response is: \n%s" % data
    print "Check: http://%s%s %s %s" % (host,uri,method,status)

def post_http(host,uri,params,headers,method="POST"):
    try:
        conn = httplib.HTTPConnection(host)
        conn.request(method,uri,params,headers)
        r = conn.getresponse()
        data = r.read()
        status = r.status
    except httplib.HTTPException as e:
        print "Error: %s" % e
    finally:
        conn.close()
    print "Response is: \n%s" % data
    print "Check: http://%s%s %s %s" % (host,uri,method,status)

if __name__ == '__main__':
    params = urllib.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'})
    headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}

    get_http('localhost.me','/a.php',method="GET")
    post_http('localhost.me','/b.php',params,headers,method="POST")

测试过程中试用的php代码如下:

a.php

<?php
echo "I love coding.";
?>

b.php

<?php
var_dump($_POST);
?>

测试

python check_http.py

Response is:
I love coding.
Check: http://localhost.me/a.php GET 200
Response is:
array(3) {
  ["@action"]=>
  string(4) "show"
  ["@number"]=>
  string(5) "12524"
  ["@type"]=>
  string(5) "issue"
}

Check: http://localhost.me/b.php POST 200

代码里get_http、post_http这两个函数可以直接合成一个,python的函数支持传不确定个参数,这里没有合是为了演示方便。