鉴客 python发送HTTP请求

来源:互联网 发布:会计证网络课程 编辑:程序博客网 时间:2024/05/20 09:08


1.
GET 方法

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


2. HEAD 方法

>>> import httplib  >>> conn = httplib.HTTPConnection("www.python.org")  >>> conn.request("HEAD","/index.html")  >>> res = conn.getresponse()  >>> print res.status, res.reason  200 OK  >>> data = res.read()  >>> print len(data)  0 >>> data == ''  True 

3. POST 方法

>>> import httplib, urllib  >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})  >>> headers = {"Content-type": "application/x-www-form-urlencoded",  ...            "Accept": "text/plain"}  >>> conn = httplib.HTTPConnection("musi-cal.mojam.com:80")  >>> conn.request("POST", "/cgi-bin/query", params, headers)  >>> response = conn.getresponse()  >>> print response.status, response.reason  200 OK  >>> data = response.read()  >>> conn.clo


使用httplib2


>>> from httplib2 import Http>>> from urllib.parse import urlencode>>> h = Http()>>> data = {"name": "Joe", "comment": "A test comment"}>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))

#!/usr/bin/python3import urllib.parseimport httplib2http = httplib2.Http()url = 'http://www.example.com/login'   body = {'USERNAME': 'foo', 'PASSWORD': 'bar'}headers = {'Content-type': 'application/x-www-form-urlencoded'}response, content = http.request(url, 'POST', headers=headers, body=urllib.parse.urlencode(body))headers = {'Cookie': response['set-cookie']}url = 'http://www.example.com/home'   response, content = http.request(url, 'GET', headers=headers)



0 0
原创粉丝点击