1.1.4 Examples

To do a simple GET request just supply the absolute URI of the resource:

import httplib2
h = httplib2.Http()
resp, content = h.request("http://bitworking.org/")
assert resp.status == 200
assert resp['content-type'] == 'text/html'

Here is more complex example that does a PUT of some text to a resource that requires authentication. The Http instance also uses a file cache in the directory .cache.

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

Here is an example that connects to a server that supports the Atom Publishing Protocol.

import httplib2
h = httplib2.Http()
h.add_credentials(myname, mypasswd)
h.follow_all_redirects = True
headers = {'Content-Type': 'application/atom+xml'}
body    = """<?xml version="1.0" ?>
    <entry xmlns="http://www.w3.org/2005/Atom">
      <title>Atom-Powered Robots Run Amok</title>
      <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
      <updated>2003-12-13T18:30:02Z</updated>
      <author><name>John Doe</name></author>
      <content>Some text.</content>
</entry>
"""
uri     = "http://www.example.com/collection/"
resp, content = h.request(uri, "POST", body=body, headers=headers)

Here is an example of providing data to an HTML form processor. In this case we presume this is a POST form. We need to take our data and format it as "application/x-www-form-urlencoded" data and use that as a body for a POST request.

>>> import httplib2
>>> import urllib
>>> data = {'name': 'fred', 'address': '123 shady lane'}
>>> body = urllib.urlencode(data)
>>> body
'name=fred&address=123+shady+lane'
>>> h = httplib2.Http()
>>> resp, content = h.request("http://example.com", method="POST", body=body)

Here is an example of using a proxy server:

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/")

\begin{center}\vbox{\input{modref.ind}
}\end{center}