本文共 1806 字,大约阅读时间需要 6 分钟。
>>> 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()
>>> 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
>>> 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)
转载地址:http://whyob.baihongyu.com/