2 # Copyright (c) Twisted Matrix Laboratories.
3 # See LICENSE for details.
6 This example demonstrates how to make a simple http client.
11 Don't forget the http:// when you type the web address!
15 from pprint import pprint
17 from twisted import version
18 from twisted.python import log
19 from twisted.internet.defer import Deferred
20 from twisted.internet import reactor
21 from twisted.internet.protocol import Protocol
22 from twisted.web.iweb import UNKNOWN_LENGTH
23 from twisted.web.http_headers import Headers
24 from twisted.web.client import Agent, ResponseDone
27 class WriteToStdout(Protocol):
28 def connectionMade(self):
29 self.onConnLost = Deferred()
31 def dataReceived(self, data):
33 Print out the html page received.
35 print 'Got some:', data
37 def connectionLost(self, reason):
38 if not reason.check(ResponseDone):
39 reason.printTraceback()
42 self.onConnLost.callback(None)
45 def main(reactor, url):
47 We create a custom UserAgent and send a GET request to a web server.
49 userAgent = 'Twisted/%s (httpclient.py)' % (version.short(),)
50 agent = Agent(reactor)
52 'GET', url, Headers({'user-agent': [userAgent]}))
53 def cbResponse(response):
55 Prints out the response returned by the web server.
57 pprint(vars(response))
58 proto = WriteToStdout()
59 if response.length is not UNKNOWN_LENGTH:
60 print 'The response body will consist of', response.length, 'bytes.'
62 print 'The response body length is unknown.'
63 response.deliverBody(proto)
64 return proto.onConnLost
65 d.addCallback(cbResponse)
67 d.addBoth(lambda ign: reactor.callWhenRunning(reactor.stop))
71 if __name__ == '__main__':
72 main(reactor, *sys.argv[1:])