2
# Copyright (c) 2009 Twisted Matrix Laboratories.
3
# See LICENSE for details.
6
from pprint import pprint
8
from twisted import version
9
from twisted.python import log
10
from twisted.internet.defer import Deferred
11
from twisted.internet import reactor
12
from twisted.internet.protocol import Protocol
13
from twisted.web.iweb import UNKNOWN_LENGTH
14
from twisted.web.http_headers import Headers
15
from twisted.web.client import Agent, ResponseDone
18
class WriteToStdout(Protocol):
19
def connectionMade(self):
20
self.onConnLost = Deferred()
22
def dataReceived(self, data):
23
print 'Got some:', data
25
def connectionLost(self, reason):
26
if not reason.check(ResponseDone):
27
reason.printTraceback()
30
self.onConnLost.callback(None)
33
def main(reactor, url):
34
userAgent = 'Twisted/%s (httpclient.py)' % (version.short(),)
35
agent = Agent(reactor)
37
'GET', url, Headers({'user-agent': [userAgent]}))
38
def cbResponse(response):
39
pprint(vars(response))
40
proto = WriteToStdout()
41
if response.length is not UNKNOWN_LENGTH:
42
print 'The response body will consist of', response.length, 'bytes.'
44
print 'The response body length is unknown.'
45
response.deliverBody(proto)
46
return proto.onConnLost
47
d.addCallback(cbResponse)
49
d.addBoth(lambda ign: reactor.callWhenRunning(reactor.stop))
53
if __name__ == '__main__':
54
main(reactor, *sys.argv[1:])