Project

General

Profile

Feature #4100 ยป net.http.rb.doc.2.patch

Revised patch that applies atop 29983 - drbrain (Eric Hodel), 12/01/2010 02:06 AM

View differences:

lib/net/http.rb (working copy)
32 32

  
33 33
  # == An HTTP client API for Ruby.
34 34
  #
35
  # For more details about HTTP, see [RFC2616](http://www.ietf.org/rfc/rfc2616.txt).
35
  # Net::HTTP provides a rich library which can be used to build HTTP
36
  # user-agents.  For more details about HTTP see
37
  # [RFC2616](http://www.ietf.org/rfc/rfc2616.txt)
36 38
  #
37
  # == Examples
39
  # Net::HTTP is designed to work closely with URI.  URI::HTTP#host,
40
  # URI::HTTP#port and URI::HTTP#request_uri are designed to work with
41
  # Net::HTTP.
38 42
  #
39
  # === Fetching Documents
43
  # If you are only performing a few GET requests you should try OpenURI.
40 44
  #
41
  # Simple GET
45
  # == How to use Net::HTTP
42 46
  #
43
  #     require 'net/http'
44
  #     Net::HTTP.get('www.example.com', '/index.html') => String
47
  # Net::HTTP provides several convenience methods for performing a GET on a
48
  # web server which are described below.
45 49
  #
46
  # Simple GET by URI object
50
  # All examples assume you have loaded Net::HTTP with:
47 51
  #
48
  #     require 'net/http'
49
  #     require 'uri'
50
  #     Net::HTTP.get(URI.parse('http://www.example.com/index.html?count=10')) => String
52
  #   require 'net/http'
51 53
  #
52
  # More generic GET with dynamic parameters
54
  # This will also require 'uri' so you don't need to require it separately.
53 55
  #
54
  #    require 'net/http'
55
  #    require 'uri'
56
  # The following example code can be used as the basis of a HTTP user-agent
57
  # which will perform a variety of request types.
56 58
  #
57
  #    uri = URI.parse('http://www.example.com/index.html')
58
  #    params = { :limit => 10, :page => 3 }
59
  #    uri.query = URI.encode_www_form(params)
60
  #    res = Net::HTTP.get_response(uri)
61
  #    puts res.body if res.is_a?(Net::HTTPSuccess)
59
  #   uri = URI.parse 'http://example.com/some_path?query=string'
62 60
  #
63
  # Even more generic GET with Basic Auth and custom header
61
  #   Net::HTTP.start uri.host, uri.port do |http|
62
  #     request = Net::HTTP::Get.new uri.request_uri
64 63
  #
65
  #    require 'net/http'
64
  #     response = http.request request # Net::HTTPResponse object
65
  #   end
66 66
  #
67
  #    uri = URI.parse('http://www.example.com/index.html?key=value')
68
  #    req = Net::HTTP::Get.new(uri.request_uri)
69
  #    req.basic_auth 'user', 'pass'
70
  #    req['X-Custom-Header'] = Time.now.to_i
71
  #    res = Net::HTTP.start(uri.hostname, uri.port) {|http|
72
  #      http.request(req)
73
  #    }
74
  #    puts res.body
67
  # Net::HTTP::start immediately creates a connection to an HTTP server which
68
  # is kept open for the duration of the block.  The connection will remain
69
  # open for multiple requests in the block if the server indicates it
70
  # supports persistent connections.
75 71
  #
76
  # Accessing Response data:
72
  # The request types Net::HTTP supports are listed below in the section "HTTP
73
  # Request Classes".
77 74
  #
78
  #     res = Net::HTTP.get_response(URI.parse('http://www.example.com/index.html'))
79
  #     # Headers
80
  #     res['Set-Cookie']            => String
81
  #     res.get_fields('set-cookie') => Array
82
  #     res.to_hash['set-cookie']    => Array
83
  #     puts "Headers: #{res.to_hash.inspect}"
84
  #     # Status
85
  #     puts res.code => '200'
86
  #     puts res.message => 'OK'
87
  #     puts res.class.name => 'HTTPOK'
88
  #     puts res.body
75
  # If you wish to re-use a connection across multiple HTTP requests without
76
  # automatically closing it you can use ::new instead of ::start.  #request
77
  # will automatically open a connection to the server if one is not currently
78
  # open.  You can manually close the connection with #close.
89 79
  #
90
  # === Posting Form Data
80
  # === Response Data
91 81
  #
92
  #     require 'net/http'
93
  #     require 'uri'
82
  #   uri = URI.parse('http://example.com/index.html')
83
  #   res = Net::HTTP.get_response(uri)
94 84
  #
95
  #     #1: Simple POST
96
  #     res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
97
  #                               {'q' => 'ruby', 'max' => '50'})
98
  #     puts res.body
85
  #   # Headers
86
  #   res['Set-Cookie']            # => String
87
  #   res.get_fields('set-cookie') # => Array
88
  #   res.to_hash['set-cookie']    # => Array
89
  #   puts "Headers: #{res.to_hash.inspect}"
99 90
  #
100
  #     #2: Detailed control of POST with authentication
91
  #   # Status
92
  #   puts res.code       # => '200'
93
  #   puts res.message    # => 'OK'
94
  #   puts res.class.name # => 'HTTPOK'
101 95
  #
102
  #     uri = URI.parse('http://www.example.com/todo.cgi')
103
  #     req = Net::HTTP::Post.new(uri.path)
104
  #     req.basic_auth 'jack', 'pass'
105
  #     req.set_form_data({'from' => '2005-01-01', 'to' => '2005-03-31'}, ';')
106
  #     res = Net::HTTP.new(uri.hostname, uri.port).start {|http| http.request(req) }
107
  #     case res
108
  #     when Net::HTTPSuccess, Net::HTTPRedirection
109
  #       # OK
96
  #   # Body
97
  #   puts res.body if res.response_body_permitted?
98
  #
99
  # === Following Redirection
100
  #
101
  # Each Net::HTTPResponse object belongs to a class for its response code.
102
  #
103
  # For example, all 2XX responses are instances of a Net::HTTPSuccess
104
  # subclass, a 3XX response is an instance of a Net::HTTPRedirection
105
  # subclass and a 200 response is an instance of the Net::HTTPOK class.  For
106
  # details of response classes, see the section "HTTP Response Classes"
107
  # below.
108
  #
109
  # Using a case statement you can handle various types of responses properly:
110
  #
111
  #   def fetch(uri_str, limit = 10)
112
  #     # You should choose a better exception.
113
  #     raise ArgumentError, 'too many HTTP redirects' if limit == 0
114
  #
115
  #     response = Net::HTTP.get_response(URI.parse(uri_str))
116
  #
117
  #     case response
118
  #     when Net::HTTPSuccess then
119
  #       response
120
  #     when Net::HTTPRedirection then
121
  #       location = response['location']
122
  #       warn "redirected to #{location}"
123
  #       fetch(location, limit - 1)
110 124
  #     else
111
  #       res.error!
125
  #       response.value
112 126
  #     end
127
  #   end
113 128
  #
114
  #     #3: Multiple values
115
  #     res = Net::HTTP.post_form(URI.parse('http://www.example.com/search.cgi'),
116
  #                               {'q' => ['ruby', 'perl'], 'max' => '50'})
117
  #     puts res.body
118
  #
119
  # === Accessing via Proxy
120
  #
121
  # Net::HTTP.Proxy is an http proxy class. It has the same
122
  # methods as Net::HTTP, but its instances always connect via a proxy,
123
  # instead of directly to the given host.
124
  #
125
  #     require 'net/http'
126
  #
127
  #     proxy_addr = 'your.proxy.host'
128
  #     proxy_port = 8080
129
  #             :
130
  #     Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
131
  #       # always connect to your.proxy.addr:8080
132
  #             :
133
  #     }
134
  #
135
  # The top-level Net::HTTP class creates objects which represent
136
  # HTTP sessions.
137
  #
138
  # Since Net::HTTP.Proxy returns Net::HTTP itself when +proxy_addr+ is nil,
139
  # there's no need to change your code depending on whether there's a proxy
140
  # or not.
141
  #
142
  # There are two additional parameters in Net::HTTP.Proxy which allow you to
143
  # specify a user name and password for the proxy:
144
  #
145
  #     Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user = nil, proxy_pass = nil)
146
  #
147
  # You can use them to work with authorization-enabled proxies:
148
  #
149
  #     require 'net/http'
150
  #     require 'uri'
151
  #
152
  #     proxy_host = 'your.proxy.host'
153
  #     proxy_port = 8080
154
  #     uri = URI.parse(ENV['http_proxy'])
155
  #     proxy_user, proxy_pass = uri.userinfo.split(/:/) if uri.userinfo
156
  #     Net::HTTP::Proxy(proxy_host, proxy_port,
157
  #                      proxy_user, proxy_pass).start('www.example.com') {|http|
158
  #       # always connect to your.proxy.addr:8080 using specified username and password
159
  #             :
160
  #     }
129
  #   print fetch('http://www.ruby-lang.org')
161 130
  #
162
  # Note that net/http does not use the HTTP_PROXY environment variable.
163
  # If you want to use a proxy, you must do so explicitly.
131
  # === POST
164 132
  #
165
  # === Following Redirection
133
  # A POST can be made using the Net::HTTP::Post request class.  This example
134
  # creates a urlencoded POST body:
166 135
  #
167
  #     require 'net/http'
168
  #     require 'uri'
136
  #   uri = URI.parse('http://www.example.com/todo.cgi')
137
  #   req = Net::HTTP::Post.new(uri.path)
138
  #   req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
169 139
  #
170
  #     def fetch(uri_str, limit = 10)
171
  #       # You should choose better exception.
172
  #       raise ArgumentError, 'HTTP redirect too deep' if limit == 0
173
  #
174
  #       response = Net::HTTP.get_response(URI.parse(uri_str))
175
  #       case response
176
  #       when Net::HTTPSuccess     then response
177
  #       when Net::HTTPRedirection then fetch(response['location'], limit - 1)
178
  #       else
179
  #         response.error!
180
  #       end
181
  #     end
140
  #   res = Net::HTTP.new(uri.hostname, uri.port).start do |http|
141
  #     http.request(req)
142
  #   end
182 143
  #
183
  #     print fetch('http://www.ruby-lang.org')
144
  #   case res
145
  #   when Net::HTTPSuccess, Net::HTTPRedirection
146
  #     # OK
147
  #   else
148
  #     res.value
149
  #   end
184 150
  #
185
  # Net::HTTPSuccess and Net::HTTPRedirection are HTTPResponse subclasses.
186
  # All HTTPResponse objects belong to their own response class, which
187
  # indicates the HTTP result status. For details of the response classes,
188
  # see the section "HTTP Response Classes".
151
  # At this time Net::HTTP does not support multipart/form-data.  To send
152
  # multipart/form-data use Net::HTTPRequest#body= and
153
  # Net::HTTPRequest#content_type=:
189 154
  #
190
  # === Full example with retrying and error reporting
155
  #   req = Net::HTTP::Post.new(uri.path)
156
  #   req.body = multipart_data
157
  #   req.content_type = 'multipart/form-data'
191 158
  #
192
  #     require 'uri'
193
  #     require 'net/http'
159
  # Other requests that can contain a body such as PUT can be created in the
160
  # same way using the corresponding request class (Net::HTTP::Put).
194 161
  #
195
  #     url = "http://www.example.com/"
162
  # === Setting Headers
196 163
  #
197
  #     # Break apart the URL
198
  #     uri = URI.parse(url)
199
  #     # Reassemble the path for the HTTP request
200
  #     if uri.query
201
  #       path = uri.path + '?' + uri.query
202
  #     else
203
  #       path = uri.path
204
  #     end
164
  # The following example performs a conditional GET using the
165
  # If-Modified-Since header.  If the files has not been modified since the
166
  # time in the header a Not Modified response will be returned.  See RFC 2616
167
  # section 9.3 for further details.
205 168
  #
206
  #     # Create a request object
207
  #     request = Net::HTTP::Get.new(path)
169
  #   uri = URI.parse('http://example.com/cached_response')
170
  #   file = File.stat 'cached_response'
208 171
  #
209
  #     # Prepare an HTTP connection object
210
  #     http = Net::HTTP.new(uri.host, uri.port)
172
  #   req = Net::HTTP::Get.new(uri.request_uri)
173
  #   req['If-Modified-Since'] = file.mtime.rfc2822
211 174
  #
212
  #     # Open the connection and issue the request, retrying up to 3 times if there
213
  #     # is a timeout
214
  #     attempts = 1
215
  #     begin
216
  #       response = http.request(request)
217
  #     rescue Exception => e
218
  #       puts e
219
  #       puts "[Retrying]"
220
  #       attempts += 1
221
  #       retry if attempts <= 3
222
  #     end
175
  #   res = Net::HTTP.start(uri.hostname, uri.port) {|http|
176
  #     http.request(req)
177
  #   }
223 178
  #
224
  #     # Report the result
225
  #     if response.kind_of? Net::HTTPSuccess
226
  #       puts response.body
227
  #     else
228
  #       raise "Error fetching #{url}: #{response.code} #{response.message}"
229
  #     end
179
  #   open 'cached_response', 'w' do |io|
180
  #     io.write res.body
181
  #   end if res.is_a?(Net::HTTPSuccess)
230 182
  #
231
  # === HTTP Request Classes
183
  # === Basic Authentication
232 184
  #
233
  # Here is HTTP request class hierarchy.
185
  # Basic authentication is performed according to
186
  # [RFC2617](http://www.ietf.org/rfc/rfc2617.txt)
234 187
  #
235
  #   Net::HTTPRequest
236
  #       Net::HTTP::Get
237
  #       Net::HTTP::Head
238
  #       Net::HTTP::Post
239
  #       Net::HTTP::Put
240
  #       Net::HTTP::Proppatch
241
  #       Net::HTTP::Lock
242
  #       Net::HTTP::Unlock
243
  #       Net::HTTP::Options
244
  #       Net::HTTP::Propfind
245
  #       Net::HTTP::Delete
246
  #       Net::HTTP::Move
247
  #       Net::HTTP::Copy
248
  #       Net::HTTP::Mkcol
249
  #       Net::HTTP::Trace
188
  #   uri = URI.parse('http://example.com/index.html?key=value')
250 189
  #
251
  # === HTTP Response Classes
190
  #   req = Net::HTTP::Get.new(uri.request_uri)
191
  #   req.basic_auth 'user', 'pass'
252 192
  #
253
  # The request() method returns a response of a specific class, depending
254
  # on the result of the HTTP request.
193
  #   res = Net::HTTP.start(uri.hostname, uri.port) {|http|
194
  #     http.request(req)
195
  #   }
196
  #   puts res.body
255 197
  #
256
  # To handle the result, you can use case/when statements. Example:
198
  # === Streaming Response Bodies
257 199
  #
258
  #     response = http.request(req)
259
  #     case response
260
  #       when Net::HTTPSuccess
261
  #         # Succeeded
262
  #       when Net::HTTPInformation
263
  #         # Continuing process
264
  #       when Net::HTTPRedirection
265
  #         # Page has moved, handle redirect
266
  #       when Net::HTTPClientError
267
  #         # Client is wrong
268
  #       when Net::HTTPServerError
269
  #         # Site is broken
270
  #       else
271
  #         # Unknown
200
  # By default Net::HTTP reads an entire response into memory.  If you are
201
  # handling large files or wish to implement a progress bar you can instead
202
  # stream the body directly to an IO.
203
  #
204
  #   uri = URI.parse 'http://example.com/large_file'
205
  #
206
  #   Net::HTTP.start uri.host, uri.port do |http|
207
  #     request = Net::HTTP::Get.new uri.request_uri
208
  #
209
  #     http.request request do |response|
210
  #       open 'large_file', 'w' do |io|
211
  #         response.read_body do |chunk|
212
  #           io.write chunk
213
  #         end
214
  #       end
272 215
  #     end
216
  #   end
217
  #
218
  # === HTTPS
219
  #
220
  # HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=.
221
  #
222
  #   uri = URI.parse 'https://secure.example.com/some_path?query=string'
223
  #
224
  #   Net::HTTP.new uri.host, uri.port
225
  #   http.use_ssl = uri.scheme == 'https'
226
  #
227
  #   http.start do
228
  #     request = Net::HTTP::Get.new uri.request_uri
229
  #
230
  #     response = http.request request # Net::HTTPResponse object
231
  #   end
232
  #
233
  # In previous versions of ruby you would need to require 'net/https' to use
234
  # HTTPS.  This is no longer true.
235
  #
236
  # === Proxies
237
  #
238
  # Net::HTTP::Proxy has the same methods as Net::HTTP but its instances always
239
  # connect via the proxy instead of directly to the given host.
240
  #
241
  #   proxy_addr = 'your.proxy.host'
242
  #   proxy_port = 8080
243
  #
244
  #   Net::HTTP::Proxy(proxy_addr, proxy_port).start('www.example.com') {|http|
245
  #     # always connect to your.proxy.addr:8080
246
  #   }
247
  #
248
  # Net::HTTP::Proxy returns a Net::HTTP instance when proxy_addr is nil so
249
  # there is no need for conditional code.
250
  #
251
  # See Net::HTTP::Proxy for further details and examples such as proxies that
252
  # require a username and password.
253
  #
254
  # == Simple Examples
255
  #
256
  # The Net::HTTP methods in the following examples do not persist
257
  # connections.  They are not recommended if you are performing many HTTP
258
  # requests.
259
  #
260
  # === GET
261
  #
262
  #   Net::HTTP.get('example.com', '/index.html') # => String
263
  #
264
  # === GET by URI
265
  #
266
  #   uri = URI.parse('http://example.com/index.html?count=10')
267
  #   Net::HTTP.get(uri) # => String
268
  #
269
  # === GET with Dynamic Parameters
270
  #
271
  #   uri = URI.parse('http://example.com/index.html')
272
  #   params = { :limit => 10, :page => 3 }
273
  #   uri.query = URI.encode_www_form(params)
274
  #
275
  #   res = Net::HTTP.get_response(uri)
276
  #   puts res.body if res.is_a?(Net::HTTPSuccess)
277
  #
278
  # === POST
279
  #
280
  #   uri = URI.parse('http://www.example.com/search.cgi')
281
  #   res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
282
  #   puts res.body
283
  #
284
  # === POST with Multiple Values
285
  #
286
  #   uri = URI.parse('http://www.example.com/search.cgi')
287
  #   res = Net::HTTP.post_form(uri, 'q' => ['ruby', 'perl'], 'max' => '50')
288
  #   puts res.body
289
  #
290
  # == HTTP Request Classes
291
  #
292
  # Here is the HTTP request class hierarchy.
293
  #
294
  # * Net::HTTPRequest
295
  #   * Net::HTTP::Get
296
  #   * Net::HTTP::Head
297
  #   * Net::HTTP::Post
298
  #   * Net::HTTP::Put
299
  #   * Net::HTTP::Proppatch
300
  #   * Net::HTTP::Lock
301
  #   * Net::HTTP::Unlock
302
  #   * Net::HTTP::Options
303
  #   * Net::HTTP::Propfind
304
  #   * Net::HTTP::Delete
305
  #   * Net::HTTP::Move
306
  #   * Net::HTTP::Copy
307
  #   * Net::HTTP::Mkcol
308
  #   * Net::HTTP::Trace
309
  #
310
  # == HTTP Response Classes
311
  #
312
  # Here is HTTP response class hierarchy.  All classes are defined in Net
313
  # module and are subclasses of Net::HTTPResponse.
314
  #
315
  # HTTPUnknownResponse:: For unhandled HTTP extenensions
316
  # HTTPInformation::                    1xx
317
  #   HTTPContinue::                        100
318
  #   HTTPSwitchProtocol::                  101
319
  # HTTPSuccess::                        2xx
320
  #   HTTPOK::                              200
321
  #   HTTPCreated::                         201
322
  #   HTTPAccepted::                        202
323
  #   HTTPNonAuthoritativeInformation::     203
324
  #   HTTPNoContent::                       204
325
  #   HTTPResetContent::                    205
326
  #   HTTPPartialContent::                  206
327
  # HTTPRedirection::                    3xx
328
  #   HTTPMultipleChoice::                  300
329
  #   HTTPMovedPermanently::                301
330
  #   HTTPFound::                           302
331
  #   HTTPSeeOther::                        303
332
  #   HTTPNotModified::                     304
333
  #   HTTPUseProxy::                        305
334
  #   HTTPTemporaryRedirect::               307
335
  # HTTPClientError::                    4xx
336
  #   HTTPBadRequest::                      400
337
  #   HTTPUnauthorized::                    401
338
  #   HTTPPaymentRequired::                 402
339
  #   HTTPForbidden::                       403
340
  #   HTTPNotFound::                        404
341
  #   HTTPMethodNotAllowed::                405
342
  #   HTTPNotAcceptable::                   406
343
  #   HTTPProxyAuthenticationRequired::     407
344
  #   HTTPRequestTimeOut::                  408
345
  #   HTTPConflict::                        409
346
  #   HTTPGone::                            410
347
  #   HTTPLengthRequired::                  411
348
  #   HTTPPreconditionFailed::              412
349
  #   HTTPRequestEntityTooLarge::           413
350
  #   HTTPRequestURITooLong::               414
351
  #   HTTPUnsupportedMediaType::            415
352
  #   HTTPRequestedRangeNotSatisfiable::    416
353
  #   HTTPExpectationFailed::               417
354
  # HTTPServerError::                    5xx
355
  #   HTTPInternalServerError::             500
356
  #   HTTPNotImplemented::                  501
357
  #   HTTPBadGateway::                      502
358
  #   HTTPServiceUnavailable::              503
359
  #   HTTPGatewayTimeOut::                  504
360
  #   HTTPVersionNotSupported::             505
273 361
  #
274
  # The HTTPResponse classes all provide +code+ and +message+ accessors to
275
  # obtain the 3-digit HTTP result code and the HTTP result message sent by
276
  # the server.
277
  #
278
  # Here is HTTP response class hierarchy.
279
  # All classes are defined in Net module.
280
  #
281
  #   HTTPResponse
282
  #       HTTPUnknownResponse
283
  #       HTTPInformation                    # 1xx
284
  #           HTTPContinue                       # 100
285
  #           HTTPSwitchProtocol                 # 101
286
  #       HTTPSuccess                        # 2xx
287
  #           HTTPOK                             # 200
288
  #           HTTPCreated                        # 201
289
  #           HTTPAccepted                       # 202
290
  #           HTTPNonAuthoritativeInformation    # 203
291
  #           HTTPNoContent                      # 204
292
  #           HTTPResetContent                   # 205
293
  #           HTTPPartialContent                 # 206
294
  #       HTTPRedirection                    # 3xx
295
  #           HTTPMultipleChoice                 # 300
296
  #           HTTPMovedPermanently               # 301
297
  #           HTTPFound                          # 302
298
  #           HTTPSeeOther                       # 303
299
  #           HTTPNotModified                    # 304
300
  #           HTTPUseProxy                       # 305
301
  #           HTTPTemporaryRedirect              # 307
302
  #       HTTPClientError                    # 4xx
303
  #           HTTPBadRequest                     # 400
304
  #           HTTPUnauthorized                   # 401
305
  #           HTTPPaymentRequired                # 402
306
  #           HTTPForbidden                      # 403
307
  #           HTTPNotFound                       # 404
308
  #           HTTPMethodNotAllowed               # 405
309
  #           HTTPNotAcceptable                  # 406
310
  #           HTTPProxyAuthenticationRequired    # 407
311
  #           HTTPRequestTimeOut                 # 408
312
  #           HTTPConflict                       # 409
313
  #           HTTPGone                           # 410
314
  #           HTTPLengthRequired                 # 411
315
  #           HTTPPreconditionFailed             # 412
316
  #           HTTPRequestEntityTooLarge          # 413
317
  #           HTTPRequestURITooLong              # 414
318
  #           HTTPUnsupportedMediaType           # 415
319
  #           HTTPRequestedRangeNotSatisfiable   # 416
320
  #           HTTPExpectationFailed              # 417
321
  #       HTTPServerError                    # 5xx
322
  #           HTTPInternalServerError            # 500
323
  #           HTTPNotImplemented                 # 501
324
  #           HTTPBadGateway                     # 502
325
  #           HTTPServiceUnavailable             # 503
326
  #           HTTPGatewayTimeOut                 # 504
327
  #           HTTPVersionNotSupported            # 505
362
  # There is also the Net::HTTPBadResponse exception which is raised when
363
  # there is a protocol error.
328 364
  #
329 365
  # == Switching Net::HTTP versions
330 366
  #
331
  # You can use net/http.rb 1.1 features (bundled with Ruby 1.6)
332
  # by calling HTTP.version_1_1. Calling Net::HTTP.version_1_2
333
  # allows you to use 1.2 features again.
367
  # You can use net/http.rb 1.1 features (bundled with Ruby 1.6) by calling
368
  # HTTP.version_1_1. Calling Net::HTTP.version_1_2 allows you to use 1.2
369
  # features again.  Do not confuse this with HTTP protocol features.
334 370
  #
335
  #     # example
336
  #     Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }
371
  #   # example
372
  #   Net::HTTP.start {|http1| ...(http1 has 1.2 features)... }
337 373
  #
338
  #     Net::HTTP.version_1_1
339
  #     Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }
374
  #   Net::HTTP.version_1_1
375
  #   Net::HTTP.start {|http2| ...(http2 has 1.1 features)... }
340 376
  #
341
  #     Net::HTTP.version_1_2
342
  #     Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }
377
  #   Net::HTTP.version_1_2
378
  #   Net::HTTP.start {|http3| ...(http3 has 1.2 features)... }
343 379
  #
344 380
  # Switching versions is NOT thread-safe.
345 381
  #
lib/net/https.rb (working copy)
2 2

  
3 3
= net/https -- SSL/TLS enhancement for Net::HTTP.
4 4

  
5
  This file has been merged with net/http.  There is no longer any need to
6
  require 'net/https' to use HTTPS.
7

  
8
  See Net::HTTP for details on how to make HTTPS connections.
9

  
5 10
== Info
6 11
  'OpenSSL for Ruby 2' project
7 12
  Copyright (C) 2001 GOTOU Yuuzou <gotoyuzo@notwork.org>
......
11 16
  This program is licenced under the same licence as Ruby.
12 17
  (See the file 'LICENCE'.)
13 18

  
14
== Example
15

  
16
Here is a simple HTTP client:
17

  
18
    require 'net/http'
19
    require 'uri'
20

  
21
    uri = URI.parse(ARGV[0] || 'http://localhost/')
22
    http = Net::HTTP.new(uri.host, uri.port)
23
    http.start {
24
      http.request_get(uri.path) {|res|
25
        print res.body
26
      }
27
    }
28

  
29
It can be replaced by the following code:
30

  
31
    require 'net/https'
32
    require 'uri'
33

  
34
    uri = URI.parse(ARGV[0] || 'https://localhost/')
35
    http = Net::HTTP.new(uri.host, uri.port)
36
    http.use_ssl = true if uri.scheme == "https"  # enable SSL/TLS
37
    http.start {
38
      http.request_get(uri.path) {|res|
39
        print res.body
40
      }
41
    }
42

  
43
== class Net::HTTP
44

  
45
=== Instance Methods
46

  
47
: use_ssl?
48
    returns true if use SSL/TLS with HTTP.
49

  
50
: use_ssl=((|true_or_false|))
51
    sets use_ssl.
52

  
53
: peer_cert
54
    return the X.509 certificates the server presented.
55

  
56
: key, key=((|key|))
57
    Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
58
    (This method is appeared in Michal Rokos's OpenSSL extension.)
59

  
60
: cert, cert=((|cert|))
61
    Sets an OpenSSL::X509::Certificate object as client certificate
62
    (This method is appeared in Michal Rokos's OpenSSL extension).
63

  
64
: ca_file, ca_file=((|path|))
65
    Sets path of a CA certification file in PEM format.
66
    The file can contrain several CA certificates.
67

  
68
: ca_path, ca_path=((|path|))
69
    Sets path of a CA certification directory containing certifications
70
    in PEM format.
71

  
72
: verify_mode, verify_mode=((|mode|))
73
    Sets the flags for server the certification verification at
74
    beginning of SSL/TLS session.
75
    OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER is acceptable.
76

  
77
: verify_callback, verify_callback=((|proc|))
78
    Sets the verify callback for the server certification verification.
79

  
80
: verify_depth, verify_depth=((|num|))
81
    Sets the maximum depth for the certificate chain verification.
82

  
83
: cert_store, cert_store=((|store|))
84
    Sets the X509::Store to verify peer certificate.
85

  
86
: ssl_timeout, ssl_timeout=((|sec|))
87
    Sets the SSL timeout seconds.
88

  
89 19
=end
90 20

  
91 21
require 'net/http'