blob: 05289b3da16b99767164b61bb71a7fa1c706b8e3 [file] [log] [blame]
Guido van Rossum41999c11997-12-09 00:12:23 +00001"""HTTP client class
Guido van Rossum23acc951994-02-21 16:36:04 +00002
Guido van Rossum41999c11997-12-09 00:12:23 +00003See the following URL for a description of the HTTP/1.0 protocol:
4http://www.w3.org/hypertext/WWW/Protocols/
5(I actually implemented it from a much earlier draft.)
6
7Example:
8
9>>> from httplib import HTTP
10>>> h = HTTP('www.python.org')
11>>> h.putrequest('GET', '/index.html')
12>>> h.putheader('Accept', 'text/html')
13>>> h.putheader('Accept', 'text/plain')
14>>> h.endheaders()
15>>> errcode, errmsg, headers = h.getreply()
16>>> if errcode == 200:
17... f = h.getfile()
18... print f.read() # Print the raw HTML
19...
20<HEAD>
21<TITLE>Python Language Home Page</TITLE>
22[...many more lines...]
23>>>
24
25Note that an HTTP object is used for a single request -- to issue a
26second request to the same server, you create a new HTTP object.
27(This is in accordance with the protocol, which uses a new TCP
28connection for each request.)
29"""
Guido van Rossum23acc951994-02-21 16:36:04 +000030
Guido van Rossum23acc951994-02-21 16:36:04 +000031import socket
32import string
Guido van Rossum65ab98c1995-08-07 20:13:02 +000033import mimetools
Guido van Rossum23acc951994-02-21 16:36:04 +000034
35HTTP_VERSION = 'HTTP/1.0'
36HTTP_PORT = 80
37
Guido van Rossum23acc951994-02-21 16:36:04 +000038class HTTP:
Guido van Rossum41999c11997-12-09 00:12:23 +000039 """This class manages a connection to an HTTP server."""
40
41 def __init__(self, host = '', port = 0):
42 """Initialize a new instance.
Guido van Rossum23acc951994-02-21 16:36:04 +000043
Guido van Rossum41999c11997-12-09 00:12:23 +000044 If specified, `host' is the name of the remote host to which
45 to connect. If specified, `port' specifies the port to which
46 to connect. By default, httplib.HTTP_PORT is used.
Guido van Rossum23acc951994-02-21 16:36:04 +000047
Guido van Rossum41999c11997-12-09 00:12:23 +000048 """
49 self.debuglevel = 0
50 self.file = None
51 if host: self.connect(host, port)
52
53 def set_debuglevel(self, debuglevel):
54 """Set the debug output level.
Guido van Rossum23acc951994-02-21 16:36:04 +000055
Guido van Rossum41999c11997-12-09 00:12:23 +000056 A non-false value results in debug messages for connection and
57 for all messages sent to and received from the server.
Guido van Rossum23acc951994-02-21 16:36:04 +000058
Guido van Rossum41999c11997-12-09 00:12:23 +000059 """
60 self.debuglevel = debuglevel
61
62 def connect(self, host, port = 0):
63 """Connect to a host on a given port.
64
65 Note: This method is automatically invoked by __init__,
66 if a host is specified during instantiation.
Guido van Rossum23acc951994-02-21 16:36:04 +000067
Guido van Rossum41999c11997-12-09 00:12:23 +000068 """
69 if not port:
70 i = string.find(host, ':')
71 if i >= 0:
72 host, port = host[:i], host[i+1:]
73 try: port = string.atoi(port)
74 except string.atoi_error:
75 raise socket.error, "nonnumeric port"
76 if not port: port = HTTP_PORT
77 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
78 if self.debuglevel > 0: print 'connect:', (host, port)
79 self.sock.connect(host, port)
80
81 def send(self, str):
82 """Send `str' to the server."""
83 if self.debuglevel > 0: print 'send:', `str`
84 self.sock.send(str)
85
86 def putrequest(self, request, selector):
87 """Send a request to the server.
Guido van Rossum23acc951994-02-21 16:36:04 +000088
Guido van Rossum41999c11997-12-09 00:12:23 +000089 `request' specifies an HTTP request method, e.g. 'GET'.
90 `selector' specifies the object being requested, e.g.
91 '/index.html'.
Guido van Rossum23acc951994-02-21 16:36:04 +000092
Guido van Rossum41999c11997-12-09 00:12:23 +000093 """
94 if not selector: selector = '/'
95 str = '%s %s %s\r\n' % (request, selector, HTTP_VERSION)
96 self.send(str)
97
98 def putheader(self, header, *args):
99 """Send a request header line to the server.
Guido van Rossum23acc951994-02-21 16:36:04 +0000100
Guido van Rossum41999c11997-12-09 00:12:23 +0000101 For example: h.putheader('Accept', 'text/html')
Guido van Rossum23acc951994-02-21 16:36:04 +0000102
Guido van Rossum41999c11997-12-09 00:12:23 +0000103 """
104 str = '%s: %s\r\n' % (header, string.joinfields(args,'\r\n\t'))
105 self.send(str)
106
107 def endheaders(self):
108 """Indicate that the last header line has been sent to the server."""
109 self.send('\r\n')
110
111 def getreply(self):
112 """Get a reply from the server.
113
114 Returns a tuple consisting of:
115 - server response code (e.g. '200' if all goes well)
116 - server response string corresponding to response code
117 - any RFC822 headers in the response from the server
Guido van Rossum23acc951994-02-21 16:36:04 +0000118
Guido van Rossum41999c11997-12-09 00:12:23 +0000119 """
120 self.file = self.sock.makefile('rb')
121 line = self.file.readline()
122 if self.debuglevel > 0: print 'reply:', `line`
123 try:
124 [ver, code, msg] = string.split(line, None, 2)
125 except ValueError:
Guido van Rossum29c46881998-01-19 22:25:24 +0000126 try:
127 [ver, code] = string.split(line, None, 1)
128 msg = ""
129 except ValueError:
130 self.headers = None
131 return -1, line, self.headers
Guido van Rossum41999c11997-12-09 00:12:23 +0000132 if ver[:5] != 'HTTP/':
133 self.headers = None
134 return -1, line, self.headers
135 errcode = string.atoi(code)
136 errmsg = string.strip(msg)
137 self.headers = mimetools.Message(self.file, 0)
138 return errcode, errmsg, self.headers
139
140 def getfile(self):
141 """Get a file object from which to receive data from the HTTP server.
142
143 NOTE: This method must not be invoked until getreplies
144 has been invoked.
145
146 """
147 return self.file
148
149 def close(self):
150 """Close the connection to the HTTP server."""
151 if self.file:
152 self.file.close()
153 self.file = None
154 if self.sock:
155 self.sock.close()
156 self.sock = None
Guido van Rossum65ab98c1995-08-07 20:13:02 +0000157
Guido van Rossum23acc951994-02-21 16:36:04 +0000158
159def test():
Guido van Rossum41999c11997-12-09 00:12:23 +0000160 """Test this module.
161
162 The test consists of retrieving and displaying the Python
163 home page, along with the error code and error string returned
164 by the www.python.org server.
165
166 """
167 import sys
168 import getopt
169 opts, args = getopt.getopt(sys.argv[1:], 'd')
170 dl = 0
171 for o, a in opts:
172 if o == '-d': dl = dl + 1
173 host = 'www.python.org'
174 selector = '/'
175 if args[0:]: host = args[0]
176 if args[1:]: selector = args[1]
177 h = HTTP()
178 h.set_debuglevel(dl)
179 h.connect(host)
180 h.putrequest('GET', selector)
181 h.endheaders()
182 errcode, errmsg, headers = h.getreply()
183 print 'errcode =', errcode
184 print 'errmsg =', errmsg
185 print
186 if headers:
187 for header in headers.headers: print string.strip(header)
188 print
189 print h.getfile().read()
Guido van Rossum23acc951994-02-21 16:36:04 +0000190
Guido van Rossuma0dfc7a1995-09-07 19:28:19 +0000191
Guido van Rossum23acc951994-02-21 16:36:04 +0000192if __name__ == '__main__':
Guido van Rossum41999c11997-12-09 00:12:23 +0000193 test()