| 1 |
#!/usr/bin/env python |
| 2 |
# Copyright (c) Twisted Matrix Laboratories. |
| 3 |
# See LICENSE for details. |
| 4 |
|
| 5 |
""" |
| 6 |
This example demonstrates how to make a simple http client. |
| 7 |
|
| 8 |
Usage: |
| 9 |
httpclient.py <url> |
| 10 |
|
| 11 |
Don't forget the http:// when you type the web address! |
| 12 |
""" |
| 13 |
|
| 14 |
import sys |
| 15 |
from pprint import pprint |
| 16 |
|
| 17 |
from twisted import version |
| 18 |
from twisted.internet import reactor |
| 19 |
from twisted.internet.defer import Deferred |
| 20 |
from twisted.internet.protocol import Protocol |
| 21 |
from twisted.python import log |
| 22 |
from twisted.web.client import Agent, ResponseDone |
| 23 |
from twisted.web.http_headers import Headers |
| 24 |
from twisted.web.iweb import UNKNOWN_LENGTH |
| 25 |
|
| 26 |
|
| 27 |
class WriteToStdout(Protocol): |
| 28 |
def connectionMade(self): |
| 29 |
self.onConnLost = Deferred() |
| 30 |
|
| 31 |
def dataReceived(self, data): |
| 32 |
""" |
| 33 |
Print out the html page received. |
| 34 |
""" |
| 35 |
print("Got some:", data) |
| 36 |
|
| 37 |
def connectionLost(self, reason): |
| 38 |
if not reason.check(ResponseDone): |
| 39 |
reason.printTraceback() |
| 40 |
else: |
| 41 |
print("Response done") |
| 42 |
self.onConnLost.callback(None) |
| 43 |
|
| 44 |
|
| 45 |
def main(reactor, url): |
| 46 |
""" |
| 47 |
We create a custom UserAgent and send a GET request to a web server. |
| 48 |
""" |
| 49 |
url = url.encode("ascii") |
| 50 |
userAgent = f"Twisted/{version.short()} (httpclient.py)".encode("ascii") |
| 51 |
agent = Agent(reactor) |
| 52 |
d = agent.request(b"GET", url, Headers({b"user-agent": [userAgent]})) |
| 53 |
|
| 54 |
def cbResponse(response): |
| 55 |
""" |
| 56 |
Prints out the response returned by the web server. |
| 57 |
""" |
| 58 |
pprint(vars(response)) |
| 59 |
proto = WriteToStdout() |
| 60 |
if response.length is not UNKNOWN_LENGTH: |
| 61 |
print("The response body will consist of", response.length, "bytes.") |
| 62 |
else: |
| 63 |
print("The response body length is unknown.") |
| 64 |
response.deliverBody(proto) |
| 65 |
return proto.onConnLost |
| 66 |
|
| 67 |
d.addCallback(cbResponse) |
| 68 |
d.addErrback(log.err) |
| 69 |
d.addBoth(lambda ign: reactor.callWhenRunning(reactor.stop)) |
| 70 |
reactor.run() |
| 71 |
|
| 72 |
|
| 73 |
if __name__ == "__main__": |
| 74 |
main(reactor, *sys.argv[1:]) |