最新消息:

httplib2 python下的http请求终结者

httplib2 admin 3542浏览 0评论

Simple Retrieval

import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://example.org/", "GET")

Authentication

import httplib2
h = httplib2.Http(".cache")
h.add_credentials('name', 'password')
resp, content = h.request("https://example.org/chap/2",   ##ssl + base认证
    "PUT", body="This is text",
    headers={'content-type':'text/plain'} )

Cache-Control

import httplib2
h = httplib2.Http(".cache")
resp, content = h.request("http://bitworking.org/")  #请求被缓存,下次还会用这个缓存而不去发送新的请求,缓存生效时间有web配置决定
 ...
resp, content = h.request("http://bitworking.org/",
    headers={'cache-control':'no-cache'})   ##设置不用缓存,当次将不用缓存,而是直接发一个新的请求

Forms

>>> from httplib2 import Http
>>> from urllib import urlencode
>>> h = Http()
>>> data = dict(name="Joe", comment="A test comment")
>>> resp, content = h.request("http://bitworking.org/news/223/Meet-Ares", "POST", urlencode(data))
>>> resp
{'status': '200', 'transfer-encoding': 'chunked', 'vary': 'Accept-Encoding,User-Agent',
 'server': 'Apache', 'connection': 'close', 'date': 'Tue, 31 Jul 2007 15:29:52 GMT',
 'content-type': 'text/html'}

Cookies

#!/usr/bin/env python

import urllib
import httplib2

http = 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.urlencode(body))

headers = {'Cookie': response['set-cookie']}   ###将获得cookie设置到请求头中,以备下次请求使用

url = 'http://www.example.com/home'
response, content = http.request(url, 'GET', headers=headers)  ##本次请求就不用带用户名,密码了

Proxies

import httplib2
import socks      ##需要第三方模块

httplib2.debuglevel=4
h = httplib2.Http(proxy_info = httplib2.ProxyInfo(socks.PROXY_TYPE_HTTP, 'localhost', 8000))
r,c = h.request("http://bitworking.org/news/")

 

另外,httplib2模块本身还有其它的对象或属性,可以通过print dir(httplib2)来查看

转载请注明:爱开源 » httplib2 python下的http请求终结者

您必须 登录 才能发表评论!