net-http 0.3.1 → 0.4.0

Sign up to get free protection for your applications and to get access to all the features.
data/lib/net/http.rb CHANGED
@@ -1,4 +1,4 @@
1
- # frozen_string_literal: false
1
+ # frozen_string_literal: true
2
2
  #
3
3
  # = net/http.rb
4
4
  #
@@ -34,72 +34,70 @@ module Net #:nodoc:
34
34
 
35
35
  # \Class \Net::HTTP provides a rich library that implements the client
36
36
  # in a client-server model that uses the \HTTP request-response protocol.
37
- # For information about \HTTP, see
37
+ # For information about \HTTP, see:
38
38
  #
39
39
  # - {Hypertext Transfer Protocol}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol].
40
40
  # - {Technical overview}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Technical_overview].
41
41
  #
42
- # Note: If you are performing only a few GET requests, consider using
43
- # {OpenURI}[https://docs.ruby-lang.org/en/master/OpenURI.html];
44
- # otherwise, read on.
45
- #
46
- # == Synopsis
47
- #
48
- # If you are already familiar with \HTTP, this synopsis may be helpful.
49
- #
50
- # {Session}[rdoc-ref:Net::HTTP@Sessions] with multiple requests for
51
- # {HTTP methods}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods]:
52
- #
53
- # Net::HTTP.start(hostname) do |http|
54
- # # Session started automatically before block execution.
55
- # http.get(path_or_uri, headers = {})
56
- # http.head(path_or_uri, headers = {})
57
- # http.post(path_or_uri, data, headers = {}) # Can also have a block.
58
- # http.put(path_or_uri, data, headers = {})
59
- # http.delete(path_or_uri, headers = {Depth: 'Infinity'})
60
- # http.options(path_or_uri, headers = {})
61
- # http.trace(path_or_uri, headers = {})
62
- # http.patch(path_or_uri, data, headers = {}) # Can also have a block.
63
- # # Session finished automatically at block exit.
64
- # end
65
- #
66
- # {Session}[rdoc-ref:Net::HTTP@Sessions] with multiple requests for
67
- # {WebDAV methods}[https://en.wikipedia.org/wiki/WebDAV#Implementation]:
68
- #
69
- # Net::HTTP.start(hostname) do |http|
70
- # # Session started automatically before block execution.
71
- # http.copy(path_or_uri, headers = {})
72
- # http.lock(path_or_uri, body, headers = {})
73
- # http.mkcol(path_or_uri, body = nil, headers = {})
74
- # http.move(path_or_uri, headers = {})
75
- # http.propfind(path_or_uri, body = nil, headers = {'Depth' => '0'})
76
- # http.proppatch(path_or_uri, body, headers = {})
77
- # http.unlock(path_or_uri, body, headers = {})
78
- # # Session finished automatically at block exit.
79
- # end
80
- #
81
- # Each of the following methods automatically starts and finishes
82
- # a {session}[rdoc-ref:Net::HTTP@Sessions] that sends a single request:
83
- #
84
- # # Return string response body.
85
- # Net::HTTP.get(hostname, path, port = 80)
86
- # Net::HTTP.get(uri, headers = {}, port = 80)
87
- #
88
- # # Write string response body to $stdout.
89
- # Net::HTTP.get_print(hostname, path_or_uri, port = 80)
90
- # Net::HTTP.get_print(uri, headers = {}, port = 80)
91
- #
92
- # # Return response as Net::HTTPResponse object.
93
- # Net::HTTP.get_response(hostname, path_or_uri, port = 80)
94
- # Net::HTTP.get_response(uri, headers = {}, port = 80)
95
- #
96
- # Net::HTTP.post(uri, data, headers = {})
97
- # Net::HTTP.post_form(uri, params)
98
- #
99
42
  # == About the Examples
100
43
  #
101
44
  # :include: doc/net-http/examples.rdoc
102
45
  #
46
+ # == Strategies
47
+ #
48
+ # - If you will make only a few GET requests,
49
+ # consider using {OpenURI}[https://docs.ruby-lang.org/en/master/OpenURI.html].
50
+ # - If you will make only a few requests of all kinds,
51
+ # consider using the various singleton convenience methods in this class.
52
+ # Each of the following methods automatically starts and finishes
53
+ # a {session}[rdoc-ref:Net::HTTP@Sessions] that sends a single request:
54
+ #
55
+ # # Return string response body.
56
+ # Net::HTTP.get(hostname, path)
57
+ # Net::HTTP.get(uri)
58
+ #
59
+ # # Write string response body to $stdout.
60
+ # Net::HTTP.get_print(hostname, path)
61
+ # Net::HTTP.get_print(uri)
62
+ #
63
+ # # Return response as Net::HTTPResponse object.
64
+ # Net::HTTP.get_response(hostname, path)
65
+ # Net::HTTP.get_response(uri)
66
+ # data = '{"title": "foo", "body": "bar", "userId": 1}'
67
+ # Net::HTTP.post(uri, data)
68
+ # params = {title: 'foo', body: 'bar', userId: 1}
69
+ # Net::HTTP.post_form(uri, params)
70
+ #
71
+ # - If performance is important, consider using sessions, which lower request overhead.
72
+ # This {session}[rdoc-ref:Net::HTTP@Sessions] has multiple requests for
73
+ # {HTTP methods}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods]
74
+ # and {WebDAV methods}[https://en.wikipedia.org/wiki/WebDAV#Implementation]:
75
+ #
76
+ # Net::HTTP.start(hostname) do |http|
77
+ # # Session started automatically before block execution.
78
+ # http.get(path)
79
+ # http.head(path)
80
+ # body = 'Some text'
81
+ # http.post(path, body) # Can also have a block.
82
+ # http.put(path, body)
83
+ # http.delete(path)
84
+ # http.options(path)
85
+ # http.trace(path)
86
+ # http.patch(path, body) # Can also have a block.
87
+ # http.copy(path)
88
+ # http.lock(path, body)
89
+ # http.mkcol(path, body)
90
+ # http.move(path)
91
+ # http.propfind(path, body)
92
+ # http.proppatch(path, body)
93
+ # http.unlock(path, body)
94
+ # # Session finished automatically at block exit.
95
+ # end
96
+ #
97
+ # The methods cited above are convenience methods that, via their few arguments,
98
+ # allow minimal control over the requests.
99
+ # For greater control, consider using {request objects}[rdoc-ref:Net::HTTPRequest].
100
+ #
103
101
  # == URIs
104
102
  #
105
103
  # On the internet, a URI
@@ -175,7 +173,7 @@ module Net #:nodoc:
175
173
  # {Request Fields}[https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields].
176
174
  # A host may also accept other custom fields.
177
175
  #
178
- # == Sessions
176
+ # == \HTTP Sessions
179
177
  #
180
178
  # A _session_ is a connection between a server (host) and a client that:
181
179
  #
@@ -183,7 +181,7 @@ module Net #:nodoc:
183
181
  # - May contain any number of requests.
184
182
  # - Is ended by instance method Net::HTTP#finish.
185
183
  #
186
- # See example sessions at the {Synopsis}[rdoc-ref:Net::HTTP@Synopsis].
184
+ # See example sessions at {Strategies}[rdoc-ref:Net::HTTP@Strategies].
187
185
  #
188
186
  # === Session Using \Net::HTTP.start
189
187
  #
@@ -264,66 +262,55 @@ module Net #:nodoc:
264
262
  #
265
263
  # == Following Redirection
266
264
  #
267
- # Each Net::HTTPResponse object belongs to a class for its response code.
268
- #
269
- # For example, all 2XX responses are instances of a Net::HTTPSuccess
270
- # subclass, a 3XX response is an instance of a Net::HTTPRedirection
271
- # subclass and a 200 response is an instance of the Net::HTTPOK class. For
272
- # details of response classes, see the section "HTTP Response Classes"
273
- # below.
265
+ # Each returned response is an instance of a subclass of Net::HTTPResponse.
266
+ # See the {response class hierarchy}[rdoc-ref:Net::HTTPResponse@Response+Subclasses].
274
267
  #
275
- # Using a case statement you can handle various types of responses properly:
268
+ # In particular, class Net::HTTPRedirection is the parent
269
+ # of all redirection classes.
270
+ # This allows you to craft a case statement to handle redirections properly:
276
271
  #
277
- # def fetch(uri_str, limit = 10)
272
+ # def fetch(uri, limit = 10)
278
273
  # # You should choose a better exception.
279
- # raise ArgumentError, 'too many HTTP redirects' if limit == 0
280
- #
281
- # response = Net::HTTP.get_response(URI(uri_str))
282
- #
283
- # case response
284
- # when Net::HTTPSuccess then
285
- # response
286
- # when Net::HTTPRedirection then
287
- # location = response['location']
288
- # warn "redirected to #{location}"
274
+ # raise ArgumentError, 'Too many HTTP redirects' if limit == 0
275
+ #
276
+ # res = Net::HTTP.get_response(URI(uri))
277
+ # case res
278
+ # when Net::HTTPSuccess # Any success class.
279
+ # res
280
+ # when Net::HTTPRedirection # Any redirection class.
281
+ # location = res['Location']
282
+ # warn "Redirected to #{location}"
289
283
  # fetch(location, limit - 1)
290
- # else
291
- # response.value
284
+ # else # Any other class.
285
+ # res.value
292
286
  # end
293
287
  # end
294
288
  #
295
- # print fetch('http://www.ruby-lang.org')
289
+ # fetch(uri)
296
290
  #
297
291
  # == Basic Authentication
298
292
  #
299
293
  # Basic authentication is performed according to
300
- # [RFC2617](http://www.ietf.org/rfc/rfc2617.txt).
301
- #
302
- # uri = URI('http://example.com/index.html?key=value')
294
+ # {RFC2617}[http://www.ietf.org/rfc/rfc2617.txt]:
303
295
  #
304
296
  # req = Net::HTTP::Get.new(uri)
305
- # req.basic_auth 'user', 'pass'
306
- #
307
- # res = Net::HTTP.start(uri.hostname, uri.port) {|http|
297
+ # req.basic_auth('user', 'pass')
298
+ # res = Net::HTTP.start(hostname) do |http|
308
299
  # http.request(req)
309
- # }
310
- # puts res.body
300
+ # end
311
301
  #
312
302
  # == Streaming Response Bodies
313
303
  #
314
- # By default Net::HTTP reads an entire response into memory. If you are
304
+ # By default \Net::HTTP reads an entire response into memory. If you are
315
305
  # handling large files or wish to implement a progress bar you can instead
316
306
  # stream the body directly to an IO.
317
307
  #
318
- # uri = URI('http://example.com/large_file')
319
- #
320
- # Net::HTTP.start(uri.host, uri.port) do |http|
321
- # request = Net::HTTP::Get.new uri
322
- #
323
- # http.request request do |response|
324
- # open 'large_file', 'w' do |io|
325
- # response.read_body do |chunk|
326
- # io.write chunk
308
+ # Net::HTTP.start(hostname) do |http|
309
+ # req = Net::HTTP::Get.new(uri)
310
+ # http.request(req) do |res|
311
+ # open('t.tmp', 'w') do |f|
312
+ # res.read_body do |chunk|
313
+ # f.write chunk
327
314
  # end
328
315
  # end
329
316
  # end
@@ -331,56 +318,411 @@ module Net #:nodoc:
331
318
  #
332
319
  # == HTTPS
333
320
  #
334
- # HTTPS is enabled for an HTTP connection by Net::HTTP#use_ssl=.
321
+ # HTTPS is enabled for an \HTTP connection by Net::HTTP#use_ssl=:
335
322
  #
336
- # uri = URI('https://secure.example.com/some_path?query=string')
337
- #
338
- # Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|
339
- # request = Net::HTTP::Get.new uri
340
- # response = http.request request # Net::HTTPResponse object
323
+ # Net::HTTP.start(hostname, :use_ssl => true) do |http|
324
+ # req = Net::HTTP::Get.new(uri)
325
+ # res = http.request(req)
341
326
  # end
342
327
  #
343
- # Or if you simply want to make a GET request, you may pass in an URI
344
- # object that has an HTTPS URL. Net::HTTP automatically turns on TLS
345
- # verification if the URI object has a 'https' URI scheme.
328
+ # Or if you simply want to make a GET request, you may pass in a URI
329
+ # object that has an \HTTPS URL. \Net::HTTP automatically turns on TLS
330
+ # verification if the URI object has a 'https' URI scheme:
331
+ #
332
+ # uri # => #<URI::HTTPS https://jsonplaceholder.typicode.com/>
333
+ # Net::HTTP.get(uri)
334
+ #
335
+ # == Proxy Server
336
+ #
337
+ # An \HTTP object can have
338
+ # a {proxy server}[https://en.wikipedia.org/wiki/Proxy_server].
339
+ #
340
+ # You can create an \HTTP object with a proxy server
341
+ # using method Net::HTTP.new or method Net::HTTP.start.
342
+ #
343
+ # The proxy may be defined either by argument +p_addr+
344
+ # or by environment variable <tt>'http_proxy'</tt>.
345
+ #
346
+ # === Proxy Using Argument +p_addr+ as a \String
346
347
  #
347
- # uri = URI('https://example.com/')
348
- # Net::HTTP.get(uri) # => String
348
+ # When argument +p_addr+ is a string hostname,
349
+ # the returned +http+ has the given host as its proxy:
349
350
  #
350
- # In previous versions of Ruby you would need to require 'net/https' to use
351
- # HTTPS. This is no longer true.
351
+ # http = Net::HTTP.new(hostname, nil, 'proxy.example')
352
+ # http.proxy? # => true
353
+ # http.proxy_from_env? # => false
354
+ # http.proxy_address # => "proxy.example"
355
+ # # These use default values.
356
+ # http.proxy_port # => 80
357
+ # http.proxy_user # => nil
358
+ # http.proxy_pass # => nil
352
359
  #
353
- # == Proxies
360
+ # The port, username, and password for the proxy may also be given:
354
361
  #
355
- # Net::HTTP will automatically create a proxy from the +http_proxy+
356
- # environment variable if it is present. To disable use of +http_proxy+,
357
- # pass +nil+ for the proxy address.
362
+ # http = Net::HTTP.new(hostname, nil, 'proxy.example', 8000, 'pname', 'ppass')
363
+ # # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>
364
+ # http.proxy? # => true
365
+ # http.proxy_from_env? # => false
366
+ # http.proxy_address # => "proxy.example"
367
+ # http.proxy_port # => 8000
368
+ # http.proxy_user # => "pname"
369
+ # http.proxy_pass # => "ppass"
358
370
  #
359
- # You may also create a custom proxy:
371
+ # === Proxy Using '<tt>ENV['http_proxy']</tt>'
360
372
  #
361
- # proxy_addr = 'your.proxy.host'
362
- # proxy_port = 8080
373
+ # When environment variable <tt>'http_proxy'</tt>
374
+ # is set to a \URI string,
375
+ # the returned +http+ will have the server at that URI as its proxy;
376
+ # note that the \URI string must have a protocol
377
+ # such as <tt>'http'</tt> or <tt>'https'</tt>:
363
378
  #
364
- # Net::HTTP.new('example.com', nil, proxy_addr, proxy_port).start { |http|
365
- # # always proxy via your.proxy.addr:8080
366
- # }
379
+ # ENV['http_proxy'] = 'http://example.com'
380
+ # http = Net::HTTP.new(hostname)
381
+ # http.proxy? # => true
382
+ # http.proxy_from_env? # => true
383
+ # http.proxy_address # => "example.com"
384
+ # # These use default values.
385
+ # http.proxy_port # => 80
386
+ # http.proxy_user # => nil
387
+ # http.proxy_pass # => nil
388
+ #
389
+ # The \URI string may include proxy username, password, and port number:
390
+ #
391
+ # ENV['http_proxy'] = 'http://pname:ppass@example.com:8000'
392
+ # http = Net::HTTP.new(hostname)
393
+ # http.proxy? # => true
394
+ # http.proxy_from_env? # => true
395
+ # http.proxy_address # => "example.com"
396
+ # http.proxy_port # => 8000
397
+ # http.proxy_user # => "pname"
398
+ # http.proxy_pass # => "ppass"
367
399
  #
368
- # See Net::HTTP.new for further details and examples such as proxies that
369
- # require a username and password.
400
+ # === Filtering Proxies
370
401
  #
371
- # == Compression
402
+ # With method Net::HTTP.new (but not Net::HTTP.start),
403
+ # you can use argument +p_no_proxy+ to filter proxies:
372
404
  #
373
- # Net::HTTP automatically adds Accept-Encoding for compression of response
374
- # bodies and automatically decompresses gzip and deflate responses unless a
375
- # Range header was sent.
405
+ # - Reject a certain address:
376
406
  #
377
- # Compression can be disabled through the Accept-Encoding: identity header.
407
+ # http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example')
408
+ # http.proxy_address # => nil
409
+ #
410
+ # - Reject certain domains or subdomains:
411
+ #
412
+ # http = Net::HTTP.new('example.com', nil, 'my.proxy.example', 8000, 'pname', 'ppass', 'proxy.example')
413
+ # http.proxy_address # => nil
414
+ #
415
+ # - Reject certain addresses and port combinations:
416
+ #
417
+ # http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example:1234')
418
+ # http.proxy_address # => "proxy.example"
419
+ #
420
+ # http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example:8000')
421
+ # http.proxy_address # => nil
422
+ #
423
+ # - Reject a list of the types above delimited using a comma:
424
+ #
425
+ # http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'my.proxy,proxy.example:8000')
426
+ # http.proxy_address # => nil
427
+ #
428
+ # http = Net::HTTP.new('example.com', nil, 'my.proxy', 8000, 'pname', 'ppass', 'my.proxy,proxy.example:8000')
429
+ # http.proxy_address # => nil
430
+ #
431
+ # == Compression and Decompression
432
+ #
433
+ # \Net::HTTP does not compress the body of a request before sending.
434
+ #
435
+ # By default, \Net::HTTP adds header <tt>'Accept-Encoding'</tt>
436
+ # to a new {request object}[rdoc-ref:Net::HTTPRequest]:
437
+ #
438
+ # Net::HTTP::Get.new(uri)['Accept-Encoding']
439
+ # # => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
440
+ #
441
+ # This requests the server to zip-encode the response body if there is one;
442
+ # the server is not required to do so.
443
+ #
444
+ # \Net::HTTP does not automatically decompress a response body
445
+ # if the response has header <tt>'Content-Range'</tt>.
446
+ #
447
+ # Otherwise decompression (or not) depends on the value of header
448
+ # {Content-Encoding}[https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#content-encoding-response-header]:
449
+ #
450
+ # - <tt>'deflate'</tt>, <tt>'gzip'</tt>, or <tt>'x-gzip'</tt>:
451
+ # decompresses the body and deletes the header.
452
+ # - <tt>'none'</tt> or <tt>'identity'</tt>:
453
+ # does not decompress the body, but deletes the header.
454
+ # - Any other value:
455
+ # leaves the body and header unchanged.
456
+ #
457
+ # == What's Here
458
+ #
459
+ # This is a categorized summary of methods and attributes.
460
+ #
461
+ # === \Net::HTTP Objects
462
+ #
463
+ # - {::new}[rdoc-ref:Net::HTTP.new]:
464
+ # Creates a new instance.
465
+ # - {#inspect}[rdoc-ref:Net::HTTP#inspect]:
466
+ # Returns a string representation of +self+.
467
+ #
468
+ # === Sessions
469
+ #
470
+ # - {::start}[rdoc-ref:Net::HTTP.start]:
471
+ # Begins a new session in a new \Net::HTTP object.
472
+ # - {#started?}[rdoc-ref:Net::HTTP#started?]
473
+ # (aliased as {#active?}[rdoc-ref:Net::HTTP#active?]):
474
+ # Returns whether in a session.
475
+ # - {#finish}[rdoc-ref:Net::HTTP#finish]:
476
+ # Ends an active session.
477
+ # - {#start}[rdoc-ref:Net::HTTP#start]:
478
+ # Begins a new session in an existing \Net::HTTP object (+self+).
479
+ #
480
+ # === Connections
481
+ #
482
+ # - {:continue_timeout}[rdoc-ref:Net::HTTP#continue_timeout]:
483
+ # Returns the continue timeout.
484
+ # - {#continue_timeout=}[rdoc-ref:Net::HTTP#continue_timeout=]:
485
+ # Sets the continue timeout seconds.
486
+ # - {:keep_alive_timeout}[rdoc-ref:Net::HTTP#keep_alive_timeout]:
487
+ # Returns the keep-alive timeout.
488
+ # - {:keep_alive_timeout=}[rdoc-ref:Net::HTTP#keep_alive_timeout=]:
489
+ # Sets the keep-alive timeout.
490
+ # - {:max_retries}[rdoc-ref:Net::HTTP#max_retries]:
491
+ # Returns the maximum retries.
492
+ # - {#max_retries=}[rdoc-ref:Net::HTTP#max_retries=]:
493
+ # Sets the maximum retries.
494
+ # - {:open_timeout}[rdoc-ref:Net::HTTP#open_timeout]:
495
+ # Returns the open timeout.
496
+ # - {:open_timeout=}[rdoc-ref:Net::HTTP#open_timeout=]:
497
+ # Sets the open timeout.
498
+ # - {:read_timeout}[rdoc-ref:Net::HTTP#read_timeout]:
499
+ # Returns the open timeout.
500
+ # - {:read_timeout=}[rdoc-ref:Net::HTTP#read_timeout=]:
501
+ # Sets the read timeout.
502
+ # - {:ssl_timeout}[rdoc-ref:Net::HTTP#ssl_timeout]:
503
+ # Returns the ssl timeout.
504
+ # - {:ssl_timeout=}[rdoc-ref:Net::HTTP#ssl_timeout=]:
505
+ # Sets the ssl timeout.
506
+ # - {:write_timeout}[rdoc-ref:Net::HTTP#write_timeout]:
507
+ # Returns the write timeout.
508
+ # - {write_timeout=}[rdoc-ref:Net::HTTP#write_timeout=]:
509
+ # Sets the write timeout.
510
+ #
511
+ # === Requests
512
+ #
513
+ # - {::get}[rdoc-ref:Net::HTTP.get]:
514
+ # Sends a GET request and returns the string response body.
515
+ # - {::get_print}[rdoc-ref:Net::HTTP.get_print]:
516
+ # Sends a GET request and write the string response body to $stdout.
517
+ # - {::get_response}[rdoc-ref:Net::HTTP.get_response]:
518
+ # Sends a GET request and returns a response object.
519
+ # - {::post_form}[rdoc-ref:Net::HTTP.post_form]:
520
+ # Sends a POST request with form data and returns a response object.
521
+ # - {::post}[rdoc-ref:Net::HTTP.post]:
522
+ # Sends a POST request with data and returns a response object.
523
+ # - {#copy}[rdoc-ref:Net::HTTP#copy]:
524
+ # Sends a COPY request and returns a response object.
525
+ # - {#delete}[rdoc-ref:Net::HTTP#delete]:
526
+ # Sends a DELETE request and returns a response object.
527
+ # - {#get}[rdoc-ref:Net::HTTP#get]:
528
+ # Sends a GET request and returns a response object.
529
+ # - {#head}[rdoc-ref:Net::HTTP#head]:
530
+ # Sends a HEAD request and returns a response object.
531
+ # - {#lock}[rdoc-ref:Net::HTTP#lock]:
532
+ # Sends a LOCK request and returns a response object.
533
+ # - {#mkcol}[rdoc-ref:Net::HTTP#mkcol]:
534
+ # Sends a MKCOL request and returns a response object.
535
+ # - {#move}[rdoc-ref:Net::HTTP#move]:
536
+ # Sends a MOVE request and returns a response object.
537
+ # - {#options}[rdoc-ref:Net::HTTP#options]:
538
+ # Sends a OPTIONS request and returns a response object.
539
+ # - {#patch}[rdoc-ref:Net::HTTP#patch]:
540
+ # Sends a PATCH request and returns a response object.
541
+ # - {#post}[rdoc-ref:Net::HTTP#post]:
542
+ # Sends a POST request and returns a response object.
543
+ # - {#propfind}[rdoc-ref:Net::HTTP#propfind]:
544
+ # Sends a PROPFIND request and returns a response object.
545
+ # - {#proppatch}[rdoc-ref:Net::HTTP#proppatch]:
546
+ # Sends a PROPPATCH request and returns a response object.
547
+ # - {#put}[rdoc-ref:Net::HTTP#put]:
548
+ # Sends a PUT request and returns a response object.
549
+ # - {#request}[rdoc-ref:Net::HTTP#request]:
550
+ # Sends a request and returns a response object.
551
+ # - {#request_get}[rdoc-ref:Net::HTTP#request_get]
552
+ # (aliased as {#get2}[rdoc-ref:Net::HTTP#get2]):
553
+ # Sends a GET request and forms a response object;
554
+ # if a block given, calls the block with the object,
555
+ # otherwise returns the object.
556
+ # - {#request_head}[rdoc-ref:Net::HTTP#request_head]
557
+ # (aliased as {#head2}[rdoc-ref:Net::HTTP#head2]):
558
+ # Sends a HEAD request and forms a response object;
559
+ # if a block given, calls the block with the object,
560
+ # otherwise returns the object.
561
+ # - {#request_post}[rdoc-ref:Net::HTTP#request_post]
562
+ # (aliased as {#post2}[rdoc-ref:Net::HTTP#post2]):
563
+ # Sends a POST request and forms a response object;
564
+ # if a block given, calls the block with the object,
565
+ # otherwise returns the object.
566
+ # - {#send_request}[rdoc-ref:Net::HTTP#send_request]:
567
+ # Sends a request and returns a response object.
568
+ # - {#trace}[rdoc-ref:Net::HTTP#trace]:
569
+ # Sends a TRACE request and returns a response object.
570
+ # - {#unlock}[rdoc-ref:Net::HTTP#unlock]:
571
+ # Sends an UNLOCK request and returns a response object.
572
+ #
573
+ # === Responses
574
+ #
575
+ # - {:close_on_empty_response}[rdoc-ref:Net::HTTP#close_on_empty_response]:
576
+ # Returns whether to close connection on empty response.
577
+ # - {:close_on_empty_response=}[rdoc-ref:Net::HTTP#close_on_empty_response=]:
578
+ # Sets whether to close connection on empty response.
579
+ # - {:ignore_eof}[rdoc-ref:Net::HTTP#ignore_eof]:
580
+ # Returns whether to ignore end-of-file when reading a response body
581
+ # with <tt>Content-Length</tt> headers.
582
+ # - {:ignore_eof=}[rdoc-ref:Net::HTTP#ignore_eof=]:
583
+ # Sets whether to ignore end-of-file when reading a response body
584
+ # with <tt>Content-Length</tt> headers.
585
+ # - {:response_body_encoding}[rdoc-ref:Net::HTTP#response_body_encoding]:
586
+ # Returns the encoding to use for the response body.
587
+ # - {#response_body_encoding=}[rdoc-ref:Net::HTTP#response_body_encoding=]:
588
+ # Sets the response body encoding.
589
+ #
590
+ # === Proxies
591
+ #
592
+ # - {:proxy_address}[rdoc-ref:Net::HTTP#proxy_address]:
593
+ # Returns the proxy address.
594
+ # - {:proxy_address=}[rdoc-ref:Net::HTTP#proxy_address=]:
595
+ # Sets the proxy address.
596
+ # - {::proxy_class?}[rdoc-ref:Net::HTTP.proxy_class?]:
597
+ # Returns whether +self+ is a proxy class.
598
+ # - {#proxy?}[rdoc-ref:Net::HTTP#proxy?]:
599
+ # Returns whether +self+ has a proxy.
600
+ # - {#proxy_address}[rdoc-ref:Net::HTTP#proxy_address]
601
+ # (aliased as {#proxyaddr}[rdoc-ref:Net::HTTP#proxyaddr]):
602
+ # Returns the proxy address.
603
+ # - {#proxy_from_env?}[rdoc-ref:Net::HTTP#proxy_from_env?]:
604
+ # Returns whether the proxy is taken from an environment variable.
605
+ # - {:proxy_from_env=}[rdoc-ref:Net::HTTP#proxy_from_env=]:
606
+ # Sets whether the proxy is to be taken from an environment variable.
607
+ # - {:proxy_pass}[rdoc-ref:Net::HTTP#proxy_pass]:
608
+ # Returns the proxy password.
609
+ # - {:proxy_pass=}[rdoc-ref:Net::HTTP#proxy_pass=]:
610
+ # Sets the proxy password.
611
+ # - {:proxy_port}[rdoc-ref:Net::HTTP#proxy_port]:
612
+ # Returns the proxy port.
613
+ # - {:proxy_port=}[rdoc-ref:Net::HTTP#proxy_port=]:
614
+ # Sets the proxy port.
615
+ # - {#proxy_user}[rdoc-ref:Net::HTTP#proxy_user]:
616
+ # Returns the proxy user name.
617
+ # - {:proxy_user=}[rdoc-ref:Net::HTTP#proxy_user=]:
618
+ # Sets the proxy user.
619
+ #
620
+ # === Security
621
+ #
622
+ # - {:ca_file}[rdoc-ref:Net::HTTP#ca_file]:
623
+ # Returns the path to a CA certification file.
624
+ # - {:ca_file=}[rdoc-ref:Net::HTTP#ca_file=]:
625
+ # Sets the path to a CA certification file.
626
+ # - {:ca_path}[rdoc-ref:Net::HTTP#ca_path]:
627
+ # Returns the path of to CA directory containing certification files.
628
+ # - {:ca_path=}[rdoc-ref:Net::HTTP#ca_path=]:
629
+ # Sets the path of to CA directory containing certification files.
630
+ # - {:cert}[rdoc-ref:Net::HTTP#cert]:
631
+ # Returns the OpenSSL::X509::Certificate object to be used for client certification.
632
+ # - {:cert=}[rdoc-ref:Net::HTTP#cert=]:
633
+ # Sets the OpenSSL::X509::Certificate object to be used for client certification.
634
+ # - {:cert_store}[rdoc-ref:Net::HTTP#cert_store]:
635
+ # Returns the X509::Store to be used for verifying peer certificate.
636
+ # - {:cert_store=}[rdoc-ref:Net::HTTP#cert_store=]:
637
+ # Sets the X509::Store to be used for verifying peer certificate.
638
+ # - {:ciphers}[rdoc-ref:Net::HTTP#ciphers]:
639
+ # Returns the available SSL ciphers.
640
+ # - {:ciphers=}[rdoc-ref:Net::HTTP#ciphers=]:
641
+ # Sets the available SSL ciphers.
642
+ # - {:extra_chain_cert}[rdoc-ref:Net::HTTP#extra_chain_cert]:
643
+ # Returns the extra X509 certificates to be added to the certificate chain.
644
+ # - {:extra_chain_cert=}[rdoc-ref:Net::HTTP#extra_chain_cert=]:
645
+ # Sets the extra X509 certificates to be added to the certificate chain.
646
+ # - {:key}[rdoc-ref:Net::HTTP#key]:
647
+ # Returns the OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
648
+ # - {:key=}[rdoc-ref:Net::HTTP#key=]:
649
+ # Sets the OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
650
+ # - {:max_version}[rdoc-ref:Net::HTTP#max_version]:
651
+ # Returns the maximum SSL version.
652
+ # - {:max_version=}[rdoc-ref:Net::HTTP#max_version=]:
653
+ # Sets the maximum SSL version.
654
+ # - {:min_version}[rdoc-ref:Net::HTTP#min_version]:
655
+ # Returns the minimum SSL version.
656
+ # - {:min_version=}[rdoc-ref:Net::HTTP#min_version=]:
657
+ # Sets the minimum SSL version.
658
+ # - {#peer_cert}[rdoc-ref:Net::HTTP#peer_cert]:
659
+ # Returns the X509 certificate chain for the session's socket peer.
660
+ # - {:ssl_version}[rdoc-ref:Net::HTTP#ssl_version]:
661
+ # Returns the SSL version.
662
+ # - {:ssl_version=}[rdoc-ref:Net::HTTP#ssl_version=]:
663
+ # Sets the SSL version.
664
+ # - {#use_ssl=}[rdoc-ref:Net::HTTP#use_ssl=]:
665
+ # Sets whether a new session is to use Transport Layer Security.
666
+ # - {#use_ssl?}[rdoc-ref:Net::HTTP#use_ssl?]:
667
+ # Returns whether +self+ uses SSL.
668
+ # - {:verify_callback}[rdoc-ref:Net::HTTP#verify_callback]:
669
+ # Returns the callback for the server certification verification.
670
+ # - {:verify_callback=}[rdoc-ref:Net::HTTP#verify_callback=]:
671
+ # Sets the callback for the server certification verification.
672
+ # - {:verify_depth}[rdoc-ref:Net::HTTP#verify_depth]:
673
+ # Returns the maximum depth for the certificate chain verification.
674
+ # - {:verify_depth=}[rdoc-ref:Net::HTTP#verify_depth=]:
675
+ # Sets the maximum depth for the certificate chain verification.
676
+ # - {:verify_hostname}[rdoc-ref:Net::HTTP#verify_hostname]:
677
+ # Returns the flags for server the certification verification at the beginning of the SSL/TLS session.
678
+ # - {:verify_hostname=}[rdoc-ref:Net::HTTP#verify_hostname=]:
679
+ # Sets he flags for server the certification verification at the beginning of the SSL/TLS session.
680
+ # - {:verify_mode}[rdoc-ref:Net::HTTP#verify_mode]:
681
+ # Returns the flags for server the certification verification at the beginning of the SSL/TLS session.
682
+ # - {:verify_mode=}[rdoc-ref:Net::HTTP#verify_mode=]:
683
+ # Sets the flags for server the certification verification at the beginning of the SSL/TLS session.
684
+ #
685
+ # === Addresses and Ports
686
+ #
687
+ # - {:address}[rdoc-ref:Net::HTTP#address]:
688
+ # Returns the string host name or host IP.
689
+ # - {::default_port}[rdoc-ref:Net::HTTP.default_port]:
690
+ # Returns integer 80, the default port to use for HTTP requests.
691
+ # - {::http_default_port}[rdoc-ref:Net::HTTP.http_default_port]:
692
+ # Returns integer 80, the default port to use for HTTP requests.
693
+ # - {::https_default_port}[rdoc-ref:Net::HTTP.https_default_port]:
694
+ # Returns integer 443, the default port to use for HTTPS requests.
695
+ # - {#ipaddr}[rdoc-ref:Net::HTTP#ipaddr]:
696
+ # Returns the IP address for the connection.
697
+ # - {#ipaddr=}[rdoc-ref:Net::HTTP#ipaddr=]:
698
+ # Sets the IP address for the connection.
699
+ # - {:local_host}[rdoc-ref:Net::HTTP#local_host]:
700
+ # Returns the string local host used to establish the connection.
701
+ # - {:local_host=}[rdoc-ref:Net::HTTP#local_host=]:
702
+ # Sets the string local host used to establish the connection.
703
+ # - {:local_port}[rdoc-ref:Net::HTTP#local_port]:
704
+ # Returns the integer local port used to establish the connection.
705
+ # - {:local_port=}[rdoc-ref:Net::HTTP#local_port=]:
706
+ # Sets the integer local port used to establish the connection.
707
+ # - {:port}[rdoc-ref:Net::HTTP#port]:
708
+ # Returns the integer port number.
709
+ #
710
+ # === \HTTP Version
711
+ #
712
+ # - {::version_1_2?}[rdoc-ref:Net::HTTP.version_1_2?]
713
+ # (aliased as {::is_version_1_2?}[rdoc-ref:Net::HTTP.is_version_1_2?]
714
+ # and {::version_1_2}[rdoc-ref:Net::HTTP.version_1_2]):
715
+ # Returns true; retained for compatibility.
716
+ #
717
+ # === Debugging
718
+ #
719
+ # - {#set_debug_output}[rdoc-ref:Net::HTTP#set_debug_output]:
720
+ # Sets the output stream for debugging.
378
721
  #
379
722
  class HTTP < Protocol
380
723
 
381
724
  # :stopdoc:
382
- VERSION = "0.3.1"
383
- Revision = %q$Revision$.split[1]
725
+ VERSION = "0.4.0"
384
726
  HTTPVersion = '1.1'
385
727
  begin
386
728
  require 'zlib'
@@ -452,6 +794,11 @@ module Net #:nodoc:
452
794
  # headers = {'Content-type' => 'application/json; charset=UTF-8'}
453
795
  # Net::HTTP.get(uri, headers)
454
796
  #
797
+ # Related:
798
+ #
799
+ # - Net::HTTP::Get: request class for \HTTP method +GET+.
800
+ # - Net::HTTP#get: convenience method for \HTTP method +GET+.
801
+ #
455
802
  def HTTP.get(uri_or_host, path_or_headers = nil, port = nil)
456
803
  get_response(uri_or_host, path_or_headers, port).body
457
804
  end
@@ -460,7 +807,7 @@ module Net #:nodoc:
460
807
  # Net::HTTP.get_response(hostname, path, port = 80) -> http_response
461
808
  # Net::HTTP:get_response(uri, headers = {}, port = uri.port) -> http_response
462
809
  #
463
- # Like Net::HTTP.get, but returns an Net::HTTPResponse object
810
+ # Like Net::HTTP.get, but returns a Net::HTTPResponse object
464
811
  # instead of the body string.
465
812
  def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block)
466
813
  if path_or_headers && !path_or_headers.is_a?(Hash)
@@ -479,16 +826,31 @@ module Net #:nodoc:
479
826
  end
480
827
  end
481
828
 
482
- # Posts data to the specified URI object.
829
+ # Posts data to a host; returns a Net::HTTPResponse object.
483
830
  #
484
- # Example:
831
+ # Argument +url+ must be a URL;
832
+ # argument +data+ must be a string:
833
+ #
834
+ # _uri = uri.dup
835
+ # _uri.path = '/posts'
836
+ # data = '{"title": "foo", "body": "bar", "userId": 1}'
837
+ # headers = {'content-type': 'application/json'}
838
+ # res = Net::HTTP.post(_uri, data, headers) # => #<Net::HTTPCreated 201 Created readbody=true>
839
+ # puts res.body
840
+ #
841
+ # Output:
842
+ #
843
+ # {
844
+ # "title": "foo",
845
+ # "body": "bar",
846
+ # "userId": 1,
847
+ # "id": 101
848
+ # }
485
849
  #
486
- # require 'net/http'
487
- # require 'uri'
850
+ # Related:
488
851
  #
489
- # Net::HTTP.post URI('http://www.example.com/api/search'),
490
- # { "q" => "ruby", "max" => "50" }.to_json,
491
- # "Content-Type" => "application/json"
852
+ # - Net::HTTP::Post: request class for \HTTP method +POST+.
853
+ # - Net::HTTP#post: convenience method for \HTTP method +POST+.
492
854
  #
493
855
  def HTTP.post(url, data, header = nil)
494
856
  start(url.hostname, url.port,
@@ -497,22 +859,25 @@ module Net #:nodoc:
497
859
  }
498
860
  end
499
861
 
500
- # Posts HTML form data to the specified URI object.
501
- # The form data must be provided as a Hash mapping from String to String.
502
- # Example:
862
+ # Posts data to a host; returns a Net::HTTPResponse object.
503
863
  #
504
- # { "cmd" => "search", "q" => "ruby", "max" => "50" }
864
+ # Argument +url+ must be a URI;
865
+ # argument +data+ must be a hash:
505
866
  #
506
- # This method also does Basic Authentication if and only if +url+.user exists.
507
- # But userinfo for authentication is deprecated (RFC3986).
508
- # So this feature will be removed.
867
+ # _uri = uri.dup
868
+ # _uri.path = '/posts'
869
+ # data = {title: 'foo', body: 'bar', userId: 1}
870
+ # res = Net::HTTP.post_form(_uri, data) # => #<Net::HTTPCreated 201 Created readbody=true>
871
+ # puts res.body
509
872
  #
510
- # Example:
511
- #
512
- # require 'net/http'
873
+ # Output:
513
874
  #
514
- # Net::HTTP.post_form URI('http://www.example.com/search.cgi'),
515
- # { "q" => "ruby", "max" => "50" }
875
+ # {
876
+ # "title": "foo",
877
+ # "body": "bar",
878
+ # "userId": "1",
879
+ # "id": 101
880
+ # }
516
881
  #
517
882
  def HTTP.post_form(url, params)
518
883
  req = Post.new(url)
@@ -525,20 +890,29 @@ module Net #:nodoc:
525
890
  end
526
891
 
527
892
  #
528
- # HTTP session management
893
+ # \HTTP session management
529
894
  #
530
895
 
531
- # The default port to use for HTTP requests; defaults to 80.
896
+ # Returns integer +80+, the default port to use for \HTTP requests:
897
+ #
898
+ # Net::HTTP.default_port # => 80
899
+ #
532
900
  def HTTP.default_port
533
901
  http_default_port()
534
902
  end
535
903
 
536
- # The default port to use for HTTP requests; defaults to 80.
904
+ # Returns integer +80+, the default port to use for \HTTP requests:
905
+ #
906
+ # Net::HTTP.http_default_port # => 80
907
+ #
537
908
  def HTTP.http_default_port
538
909
  80
539
910
  end
540
911
 
541
- # The default port to use for HTTPS requests; defaults to 443.
912
+ # Returns integer +443+, the default port to use for HTTPS requests:
913
+ #
914
+ # Net::HTTP.https_default_port # => 443
915
+ #
542
916
  def HTTP.https_default_port
543
917
  443
544
918
  end
@@ -548,19 +922,39 @@ module Net #:nodoc:
548
922
  end
549
923
 
550
924
  # :call-seq:
551
- # HTTP.start(address, port, p_addr, p_port, p_user, p_pass) {|http| ... }
552
- # HTTP.start(address, port=nil, p_addr=:ENV, p_port=nil, p_user=nil, p_pass=nil, opt) {|http| ... }
553
- # Creates a new \Net::HTTP object,
554
- # opens a TCP connection and \HTTP session.
925
+ # HTTP.start(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, opts) -> http
926
+ # HTTP.start(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, opts) {|http| ... } -> object
555
927
  #
556
- # Argument +address+ is the hostname or IP address of the server.
928
+ # Creates a new \Net::HTTP object, +http+, via \Net::HTTP.new:
929
+ #
930
+ # - For arguments +address+ and +port+, see Net::HTTP.new.
931
+ # - For proxy-defining arguments +p_addr+ through +p_pass+,
932
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
933
+ # - For argument +opts+, see below.
934
+ #
935
+ # With no block given:
936
+ #
937
+ # - Calls <tt>http.start</tt> with no block (see #start),
938
+ # which opens a TCP connection and \HTTP session.
939
+ # - Returns +http+.
940
+ # - The caller should call #finish to close the session:
941
+ #
942
+ # http = Net::HTTP.start(hostname)
943
+ # http.started? # => true
944
+ # http.finish
945
+ # http.started? # => false
557
946
  #
558
947
  # With a block given:
559
948
  #
560
- # - Passes the object to the given block,
561
- # which may make any number of requests to the host.
562
- # - Closes the \HTTP session on block exit.
563
- # - Returns the block's value.
949
+ # - Calls <tt>http.start</tt> with the block (see #start), which:
950
+ #
951
+ # - Opens a TCP connection and \HTTP session.
952
+ # - Calls the block,
953
+ # which may make any number of requests to the host.
954
+ # - Closes the \HTTP session and TCP connection on block exit.
955
+ # - Returns the block's value +object+.
956
+ #
957
+ # - Returns +object+.
564
958
  #
565
959
  # Example:
566
960
  #
@@ -585,19 +979,7 @@ module Net #:nodoc:
585
979
  # "completed": false
586
980
  # }
587
981
  #
588
- # With no block given, returns the \Net::HTTP object;
589
- # the caller should call #finish to close the session.
590
- #
591
- # Other arguments:
592
- #
593
- # - +port+: Server port number.
594
- # - +p_addr+: Proxy address.
595
- # - +p_port+: Proxy port.
596
- # - +p_user+: Proxy user name.
597
- # - +p_pass+: Proxy password.
598
- # - +opts+: Optional options hash.
599
- #
600
- # The options hash +opts+ sets certain values,
982
+ # If the last argument given is a hash, it is the +opts+ hash,
601
983
  # where each key is a method or accessor to be called,
602
984
  # and its value is the value to be set.
603
985
  #
@@ -622,6 +1004,9 @@ module Net #:nodoc:
622
1004
  # - #verify_mode
623
1005
  # - #write_timeout
624
1006
  #
1007
+ # Note: If +port+ is +nil+ and <tt>opts[:use_ssl]</tt> is a truthy value,
1008
+ # the value passed to +new+ is Net::HTTP.https_default_port, not +port+.
1009
+ #
625
1010
  def HTTP.start(address, *arg, &block) # :yield: +http+
626
1011
  arg.pop if opt = Hash.try_convert(arg[-1])
627
1012
  port, p_addr, p_port, p_user, p_pass = *arg
@@ -648,25 +1033,34 @@ module Net #:nodoc:
648
1033
  alias newobj new # :nodoc:
649
1034
  end
650
1035
 
651
- # Creates a new Net::HTTP object without opening a TCP connection or
652
- # HTTP session.
1036
+ # Returns a new \Net::HTTP object +http+
1037
+ # (but does not open a TCP connection or \HTTP session).
1038
+ #
1039
+ # With only string argument +address+ given
1040
+ # (and <tt>ENV['http_proxy']</tt> undefined or +nil+),
1041
+ # the returned +http+:
1042
+ #
1043
+ # - Has the given address.
1044
+ # - Has the default port number, Net::HTTP.default_port (80).
1045
+ # - Has no proxy.
1046
+ #
1047
+ # Example:
653
1048
  #
654
- # The +address+ should be a DNS hostname or IP address, the +port+ is the
655
- # port the server operates on. If no +port+ is given the default port for
656
- # HTTP or HTTPS is used.
1049
+ # http = Net::HTTP.new(hostname)
1050
+ # # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>
1051
+ # http.address # => "jsonplaceholder.typicode.com"
1052
+ # http.port # => 80
1053
+ # http.proxy? # => false
1054
+ #
1055
+ # With integer argument +port+ also given,
1056
+ # the returned +http+ has the given port:
657
1057
  #
658
- # If none of the +p_+ arguments are given, the proxy host and port are
659
- # taken from the +http_proxy+ environment variable (or its uppercase
660
- # equivalent) if present. If the proxy requires authentication you must
661
- # supply it by hand. See URI::Generic#find_proxy for details of proxy
662
- # detection from the environment. To disable proxy detection set +p_addr+
663
- # to nil.
1058
+ # http = Net::HTTP.new(hostname, 8000)
1059
+ # # => #<Net::HTTP jsonplaceholder.typicode.com:8000 open=false>
1060
+ # http.port # => 8000
664
1061
  #
665
- # If you are connecting to a custom proxy, +p_addr+ specifies the DNS name
666
- # or IP address of the proxy host, +p_port+ the port to use to access the
667
- # proxy, +p_user+ and +p_pass+ the username and password if authorization
668
- # is required to use the proxy, and p_no_proxy hosts which do not
669
- # use the proxy.
1062
+ # For proxy-defining arguments +p_addr+ through +p_no_proxy+,
1063
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
670
1064
  #
671
1065
  def HTTP.new(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, p_no_proxy = nil)
672
1066
  http = super address, port
@@ -680,7 +1074,7 @@ module Net #:nodoc:
680
1074
  elsif p_addr == :ENV then
681
1075
  http.proxy_from_env = true
682
1076
  else
683
- if p_addr && p_no_proxy && !URI::Generic.use_proxy?(p_addr, p_addr, p_port, p_no_proxy)
1077
+ if p_addr && p_no_proxy && !URI::Generic.use_proxy?(address, address, port, p_no_proxy)
684
1078
  p_addr = nil
685
1079
  p_port = nil
686
1080
  end
@@ -693,10 +1087,10 @@ module Net #:nodoc:
693
1087
  http
694
1088
  end
695
1089
 
696
- # Creates a new Net::HTTP object for the specified server address,
697
- # without opening the TCP connection or initializing the HTTP session.
1090
+ # Creates a new \Net::HTTP object for the specified server address,
1091
+ # without opening the TCP connection or initializing the \HTTP session.
698
1092
  # The +address+ should be a DNS hostname or IP address.
699
- def initialize(address, port = nil)
1093
+ def initialize(address, port = nil) # :nodoc:
700
1094
  @address = address
701
1095
  @port = (port || HTTP.default_port)
702
1096
  @ipaddr = nil
@@ -733,6 +1127,11 @@ module Net #:nodoc:
733
1127
  end
734
1128
  end
735
1129
 
1130
+ # Returns a string representation of +self+:
1131
+ #
1132
+ # Net::HTTP.new(hostname).inspect
1133
+ # # => "#<Net::HTTP jsonplaceholder.typicode.com:80 open=false>"
1134
+ #
736
1135
  def inspect
737
1136
  "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
738
1137
  end
@@ -740,83 +1139,184 @@ module Net #:nodoc:
740
1139
  # *WARNING* This method opens a serious security hole.
741
1140
  # Never use this method in production code.
742
1141
  #
743
- # Sets an output stream for debugging.
1142
+ # Sets the output stream for debugging:
744
1143
  #
745
1144
  # http = Net::HTTP.new(hostname)
746
- # http.set_debug_output $stderr
747
- # http.start { .... }
1145
+ # File.open('t.tmp', 'w') do |file|
1146
+ # http.set_debug_output(file)
1147
+ # http.start
1148
+ # http.get('/nosuch/1')
1149
+ # http.finish
1150
+ # end
1151
+ # puts File.read('t.tmp')
1152
+ #
1153
+ # Output:
1154
+ #
1155
+ # opening connection to jsonplaceholder.typicode.com:80...
1156
+ # opened
1157
+ # <- "GET /nosuch/1 HTTP/1.1\r\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\r\nAccept: */*\r\nUser-Agent: Ruby\r\nHost: jsonplaceholder.typicode.com\r\n\r\n"
1158
+ # -> "HTTP/1.1 404 Not Found\r\n"
1159
+ # -> "Date: Mon, 12 Dec 2022 21:14:11 GMT\r\n"
1160
+ # -> "Content-Type: application/json; charset=utf-8\r\n"
1161
+ # -> "Content-Length: 2\r\n"
1162
+ # -> "Connection: keep-alive\r\n"
1163
+ # -> "X-Powered-By: Express\r\n"
1164
+ # -> "X-Ratelimit-Limit: 1000\r\n"
1165
+ # -> "X-Ratelimit-Remaining: 999\r\n"
1166
+ # -> "X-Ratelimit-Reset: 1670879660\r\n"
1167
+ # -> "Vary: Origin, Accept-Encoding\r\n"
1168
+ # -> "Access-Control-Allow-Credentials: true\r\n"
1169
+ # -> "Cache-Control: max-age=43200\r\n"
1170
+ # -> "Pragma: no-cache\r\n"
1171
+ # -> "Expires: -1\r\n"
1172
+ # -> "X-Content-Type-Options: nosniff\r\n"
1173
+ # -> "Etag: W/\"2-vyGp6PvFo4RvsFtPoIWeCReyIC8\"\r\n"
1174
+ # -> "Via: 1.1 vegur\r\n"
1175
+ # -> "CF-Cache-Status: MISS\r\n"
1176
+ # -> "Server-Timing: cf-q-config;dur=1.3000000762986e-05\r\n"
1177
+ # -> "Report-To: {\"endpoints\":[{\"url\":\"https:\\/\\/a.nel.cloudflare.com\\/report\\/v3?s=yOr40jo%2BwS1KHzhTlVpl54beJ5Wx2FcG4gGV0XVrh3X9OlR5q4drUn2dkt5DGO4GDcE%2BVXT7CNgJvGs%2BZleIyMu8CLieFiDIvOviOY3EhHg94m0ZNZgrEdpKD0S85S507l1vsEwEHkoTm%2Ff19SiO\"}],\"group\":\"cf-nel\",\"max_age\":604800}\r\n"
1178
+ # -> "NEL: {\"success_fraction\":0,\"report_to\":\"cf-nel\",\"max_age\":604800}\r\n"
1179
+ # -> "Server: cloudflare\r\n"
1180
+ # -> "CF-RAY: 778977dc484ce591-DFW\r\n"
1181
+ # -> "alt-svc: h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400\r\n"
1182
+ # -> "\r\n"
1183
+ # reading 2 bytes...
1184
+ # -> "{}"
1185
+ # read 2 bytes
1186
+ # Conn keep-alive
748
1187
  #
749
1188
  def set_debug_output(output)
750
1189
  warn 'Net::HTTP#set_debug_output called after HTTP started', uplevel: 1 if started?
751
1190
  @debug_output = output
752
1191
  end
753
1192
 
754
- # The DNS host name or IP address to connect to.
1193
+ # Returns the string host name or host IP given as argument +address+ in ::new.
755
1194
  attr_reader :address
756
1195
 
757
- # The port number to connect to.
1196
+ # Returns the integer port number given as argument +port+ in ::new.
758
1197
  attr_reader :port
759
1198
 
760
- # The local host used to establish the connection.
1199
+ # Sets or returns the string local host used to establish the connection;
1200
+ # initially +nil+.
761
1201
  attr_accessor :local_host
762
1202
 
763
- # The local port used to establish the connection.
1203
+ # Sets or returns the integer local port used to establish the connection;
1204
+ # initially +nil+.
764
1205
  attr_accessor :local_port
765
1206
 
766
- # The encoding to use for the response body. If Encoding, uses the
767
- # specified encoding. If other true value, tries to detect the response
768
- # body encoding.
1207
+ # Returns the encoding to use for the response body;
1208
+ # see #response_body_encoding=.
769
1209
  attr_reader :response_body_encoding
770
1210
 
771
- # Set the encoding to use for the response body. If given a String, find
772
- # the related Encoding.
1211
+ # Sets the encoding to be used for the response body;
1212
+ # returns the encoding.
1213
+ #
1214
+ # The given +value+ may be:
1215
+ #
1216
+ # - An Encoding object.
1217
+ # - The name of an encoding.
1218
+ # - An alias for an encoding name.
1219
+ #
1220
+ # See {Encoding}[https://docs.ruby-lang.org/en/master/Encoding.html].
1221
+ #
1222
+ # Examples:
1223
+ #
1224
+ # http = Net::HTTP.new(hostname)
1225
+ # http.response_body_encoding = Encoding::US_ASCII # => #<Encoding:US-ASCII>
1226
+ # http.response_body_encoding = 'US-ASCII' # => "US-ASCII"
1227
+ # http.response_body_encoding = 'ASCII' # => "ASCII"
1228
+ #
773
1229
  def response_body_encoding=(value)
774
1230
  value = Encoding.find(value) if value.is_a?(String)
775
1231
  @response_body_encoding = value
776
1232
  end
777
1233
 
1234
+ # Sets whether to determine the proxy from environment variable
1235
+ # '<tt>ENV['http_proxy']</tt>';
1236
+ # see {Proxy Using ENV['http_proxy']}[rdoc-ref:Net::HTTP@Proxy+Using+-27ENV-5B-27http_proxy-27-5D-27].
778
1237
  attr_writer :proxy_from_env
1238
+
1239
+ # Sets the proxy address;
1240
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
779
1241
  attr_writer :proxy_address
1242
+
1243
+ # Sets the proxy port;
1244
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
780
1245
  attr_writer :proxy_port
1246
+
1247
+ # Sets the proxy user;
1248
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
781
1249
  attr_writer :proxy_user
1250
+
1251
+ # Sets the proxy password;
1252
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
782
1253
  attr_writer :proxy_pass
783
1254
 
784
- # The IP address to connect to/used to connect to
1255
+ # Returns the IP address for the connection.
1256
+ #
1257
+ # If the session has not been started,
1258
+ # returns the value set by #ipaddr=,
1259
+ # or +nil+ if it has not been set:
1260
+ #
1261
+ # http = Net::HTTP.new(hostname)
1262
+ # http.ipaddr # => nil
1263
+ # http.ipaddr = '172.67.155.76'
1264
+ # http.ipaddr # => "172.67.155.76"
1265
+ #
1266
+ # If the session has been started,
1267
+ # returns the IP address from the socket:
1268
+ #
1269
+ # http = Net::HTTP.new(hostname)
1270
+ # http.start
1271
+ # http.ipaddr # => "172.67.155.76"
1272
+ # http.finish
1273
+ #
785
1274
  def ipaddr
786
1275
  started? ? @socket.io.peeraddr[3] : @ipaddr
787
1276
  end
788
1277
 
789
- # Set the IP address to connect to
1278
+ # Sets the IP address for the connection:
1279
+ #
1280
+ # http = Net::HTTP.new(hostname)
1281
+ # http.ipaddr # => nil
1282
+ # http.ipaddr = '172.67.155.76'
1283
+ # http.ipaddr # => "172.67.155.76"
1284
+ #
1285
+ # The IP address may not be set if the session has been started.
790
1286
  def ipaddr=(addr)
791
1287
  raise IOError, "ipaddr value changed, but session already started" if started?
792
1288
  @ipaddr = addr
793
1289
  end
794
1290
 
795
- # Number of seconds to wait for the connection to open. Any number
796
- # may be used, including Floats for fractional seconds. If the HTTP
797
- # object cannot open a connection in this many seconds, it raises a
798
- # Net::OpenTimeout exception. The default value is 60 seconds.
1291
+ # Sets or returns the numeric (\Integer or \Float) number of seconds
1292
+ # to wait for a connection to open;
1293
+ # initially 60.
1294
+ # If the connection is not made in the given interval,
1295
+ # an exception is raised.
799
1296
  attr_accessor :open_timeout
800
1297
 
801
- # Number of seconds to wait for one block to be read (via one read(2)
802
- # call). Any number may be used, including Floats for fractional
803
- # seconds. If the HTTP object cannot read data in this many seconds,
804
- # it raises a Net::ReadTimeout exception. The default value is 60 seconds.
1298
+ # Returns the numeric (\Integer or \Float) number of seconds
1299
+ # to wait for one block to be read (via one read(2) call);
1300
+ # see #read_timeout=.
805
1301
  attr_reader :read_timeout
806
1302
 
807
- # Number of seconds to wait for one block to be written (via one write(2)
808
- # call). Any number may be used, including Floats for fractional
809
- # seconds. If the HTTP object cannot write data in this many seconds,
810
- # it raises a Net::WriteTimeout exception. The default value is 60 seconds.
811
- # Net::WriteTimeout is not raised on Windows.
1303
+ # Returns the numeric (\Integer or \Float) number of seconds
1304
+ # to wait for one block to be written (via one write(2) call);
1305
+ # see #write_timeout=.
812
1306
  attr_reader :write_timeout
813
1307
 
814
- # Maximum number of times to retry an idempotent request in case of
815
- # Net::ReadTimeout, IOError, EOFError, Errno::ECONNRESET,
1308
+ # Sets the maximum number of times to retry an idempotent request in case of
1309
+ # \Net::ReadTimeout, IOError, EOFError, Errno::ECONNRESET,
816
1310
  # Errno::ECONNABORTED, Errno::EPIPE, OpenSSL::SSL::SSLError,
817
1311
  # Timeout::Error.
818
- # Should be a non-negative integer number. Zero means no retries.
819
- # The default value is 1.
1312
+ # The initial value is 1.
1313
+ #
1314
+ # Argument +retries+ must be a non-negative numeric value:
1315
+ #
1316
+ # http = Net::HTTP.new(hostname)
1317
+ # http.max_retries = 2 # => 2
1318
+ # http.max_retries # => 2
1319
+ #
820
1320
  def max_retries=(retries)
821
1321
  retries = retries.to_int
822
1322
  if retries < 0
@@ -825,59 +1325,113 @@ module Net #:nodoc:
825
1325
  @max_retries = retries
826
1326
  end
827
1327
 
1328
+ # Returns the maximum number of times to retry an idempotent request;
1329
+ # see #max_retries=.
828
1330
  attr_reader :max_retries
829
1331
 
830
- # Setter for the read_timeout attribute.
1332
+ # Sets the read timeout, in seconds, for +self+ to integer +sec+;
1333
+ # the initial value is 60.
1334
+ #
1335
+ # Argument +sec+ must be a non-negative numeric value:
1336
+ #
1337
+ # http = Net::HTTP.new(hostname)
1338
+ # http.read_timeout # => 60
1339
+ # http.get('/todos/1') # => #<Net::HTTPOK 200 OK readbody=true>
1340
+ # http.read_timeout = 0
1341
+ # http.get('/todos/1') # Raises Net::ReadTimeout.
1342
+ #
831
1343
  def read_timeout=(sec)
832
1344
  @socket.read_timeout = sec if @socket
833
1345
  @read_timeout = sec
834
1346
  end
835
1347
 
836
- # Setter for the write_timeout attribute.
1348
+ # Sets the write timeout, in seconds, for +self+ to integer +sec+;
1349
+ # the initial value is 60.
1350
+ #
1351
+ # Argument +sec+ must be a non-negative numeric value:
1352
+ #
1353
+ # _uri = uri.dup
1354
+ # _uri.path = '/posts'
1355
+ # body = 'bar' * 200000
1356
+ # data = <<EOF
1357
+ # {"title": "foo", "body": "#{body}", "userId": "1"}
1358
+ # EOF
1359
+ # headers = {'content-type': 'application/json'}
1360
+ # http = Net::HTTP.new(hostname)
1361
+ # http.write_timeout # => 60
1362
+ # http.post(_uri.path, data, headers)
1363
+ # # => #<Net::HTTPCreated 201 Created readbody=true>
1364
+ # http.write_timeout = 0
1365
+ # http.post(_uri.path, data, headers) # Raises Net::WriteTimeout.
1366
+ #
837
1367
  def write_timeout=(sec)
838
1368
  @socket.write_timeout = sec if @socket
839
1369
  @write_timeout = sec
840
1370
  end
841
1371
 
842
- # Seconds to wait for 100 Continue response. If the HTTP object does not
843
- # receive a response in this many seconds it sends the request body. The
844
- # default value is +nil+.
1372
+ # Returns the continue timeout value;
1373
+ # see continue_timeout=.
845
1374
  attr_reader :continue_timeout
846
1375
 
847
- # Setter for the continue_timeout attribute.
1376
+ # Sets the continue timeout value,
1377
+ # which is the number of seconds to wait for an expected 100 Continue response.
1378
+ # If the \HTTP object does not receive a response in this many seconds
1379
+ # it sends the request body.
848
1380
  def continue_timeout=(sec)
849
1381
  @socket.continue_timeout = sec if @socket
850
1382
  @continue_timeout = sec
851
1383
  end
852
1384
 
853
- # Seconds to reuse the connection of the previous request.
854
- # If the idle time is less than this Keep-Alive Timeout,
855
- # Net::HTTP reuses the TCP/IP socket used by the previous communication.
856
- # The default value is 2 seconds.
1385
+ # Sets or returns the numeric (\Integer or \Float) number of seconds
1386
+ # to keep the connection open after a request is sent;
1387
+ # initially 2.
1388
+ # If a new request is made during the given interval,
1389
+ # the still-open connection is used;
1390
+ # otherwise the connection will have been closed
1391
+ # and a new connection is opened.
857
1392
  attr_accessor :keep_alive_timeout
858
1393
 
859
- # Whether to ignore EOF when reading response bodies with defined
860
- # Content-Length headers. For backwards compatibility, the default is true.
1394
+ # Sets or returns whether to ignore end-of-file when reading a response body
1395
+ # with <tt>Content-Length</tt> headers;
1396
+ # initially +true+.
861
1397
  attr_accessor :ignore_eof
862
1398
 
863
- # Returns true if the HTTP session has been started.
1399
+ # Returns +true+ if the \HTTP session has been started:
1400
+ #
1401
+ # http = Net::HTTP.new(hostname)
1402
+ # http.started? # => false
1403
+ # http.start
1404
+ # http.started? # => true
1405
+ # http.finish # => nil
1406
+ # http.started? # => false
1407
+ #
1408
+ # Net::HTTP.start(hostname) do |http|
1409
+ # http.started?
1410
+ # end # => true
1411
+ # http.started? # => false
1412
+ #
864
1413
  def started?
865
1414
  @started
866
1415
  end
867
1416
 
868
1417
  alias active? started? #:nodoc: obsolete
869
1418
 
1419
+ # Sets or returns whether to close the connection when the response is empty;
1420
+ # initially +false+.
870
1421
  attr_accessor :close_on_empty_response
871
1422
 
872
- # Returns true if SSL/TLS is being used with HTTP.
1423
+ # Returns +true+ if +self+ uses SSL, +false+ otherwise.
1424
+ # See Net::HTTP#use_ssl=.
873
1425
  def use_ssl?
874
1426
  @use_ssl
875
1427
  end
876
1428
 
877
- # Turn on/off SSL.
878
- # This flag must be set before starting session.
879
- # If you change use_ssl value after session started,
880
- # a Net::HTTP object raises IOError.
1429
+ # Sets whether a new session is to use
1430
+ # {Transport Layer Security}[https://en.wikipedia.org/wiki/Transport_Layer_Security]:
1431
+ #
1432
+ # Raises IOError if attempting to change during a session.
1433
+ #
1434
+ # Raises OpenSSL::SSL::SSLError if the port is not an HTTPS port.
881
1435
  def use_ssl=(flag)
882
1436
  flag = flag ? true : false
883
1437
  if started? and @use_ssl != flag
@@ -902,7 +1456,7 @@ module Net #:nodoc:
902
1456
  :@verify_depth,
903
1457
  :@verify_mode,
904
1458
  :@verify_hostname,
905
- ]
1459
+ ] # :nodoc:
906
1460
  SSL_ATTRIBUTES = [
907
1461
  :ca_file,
908
1462
  :ca_path,
@@ -919,64 +1473,67 @@ module Net #:nodoc:
919
1473
  :verify_depth,
920
1474
  :verify_mode,
921
1475
  :verify_hostname,
922
- ]
1476
+ ] # :nodoc:
923
1477
 
924
- # Sets path of a CA certification file in PEM format.
925
- #
926
- # The file can contain several CA certificates.
1478
+ # Sets or returns the path to a CA certification file in PEM format.
927
1479
  attr_accessor :ca_file
928
1480
 
929
- # Sets path of a CA certification directory containing certifications in
930
- # PEM format.
1481
+ # Sets or returns the path of to CA directory
1482
+ # containing certification files in PEM format.
931
1483
  attr_accessor :ca_path
932
1484
 
933
- # Sets an OpenSSL::X509::Certificate object as client certificate.
934
- # (This method is appeared in Michal Rokos's OpenSSL extension).
1485
+ # Sets or returns the OpenSSL::X509::Certificate object
1486
+ # to be used for client certification.
935
1487
  attr_accessor :cert
936
1488
 
937
- # Sets the X509::Store to verify peer certificate.
1489
+ # Sets or returns the X509::Store to be used for verifying peer certificate.
938
1490
  attr_accessor :cert_store
939
1491
 
940
- # Sets the available ciphers. See OpenSSL::SSL::SSLContext#ciphers=
1492
+ # Sets or returns the available SSL ciphers.
1493
+ # See {OpenSSL::SSL::SSLContext#ciphers=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-ciphers-3D].
941
1494
  attr_accessor :ciphers
942
1495
 
943
- # Sets the extra X509 certificates to be added to the certificate chain.
944
- # See OpenSSL::SSL::SSLContext#extra_chain_cert=
1496
+ # Sets or returns the extra X509 certificates to be added to the certificate chain.
1497
+ # See {OpenSSL::SSL::SSLContext#add_certificate}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-add_certificate].
945
1498
  attr_accessor :extra_chain_cert
946
1499
 
947
- # Sets an OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
948
- # (This method is appeared in Michal Rokos's OpenSSL extension.)
1500
+ # Sets or returns the OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
949
1501
  attr_accessor :key
950
1502
 
951
- # Sets the SSL timeout seconds.
1503
+ # Sets or returns the SSL timeout seconds.
952
1504
  attr_accessor :ssl_timeout
953
1505
 
954
- # Sets the SSL version. See OpenSSL::SSL::SSLContext#ssl_version=
1506
+ # Sets or returns the SSL version.
1507
+ # See {OpenSSL::SSL::SSLContext#ssl_version=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-ssl_version-3D].
955
1508
  attr_accessor :ssl_version
956
1509
 
957
- # Sets the minimum SSL version. See OpenSSL::SSL::SSLContext#min_version=
1510
+ # Sets or returns the minimum SSL version.
1511
+ # See {OpenSSL::SSL::SSLContext#min_version=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-min_version-3D].
958
1512
  attr_accessor :min_version
959
1513
 
960
- # Sets the maximum SSL version. See OpenSSL::SSL::SSLContext#max_version=
1514
+ # Sets or returns the maximum SSL version.
1515
+ # See {OpenSSL::SSL::SSLContext#max_version=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#method-i-max_version-3D].
961
1516
  attr_accessor :max_version
962
1517
 
963
- # Sets the verify callback for the server certification verification.
1518
+ # Sets or returns the callback for the server certification verification.
964
1519
  attr_accessor :verify_callback
965
1520
 
966
- # Sets the maximum depth for the certificate chain verification.
1521
+ # Sets or returns the maximum depth for the certificate chain verification.
967
1522
  attr_accessor :verify_depth
968
1523
 
969
- # Sets the flags for server the certification verification at beginning of
970
- # SSL/TLS session.
971
- #
1524
+ # Sets or returns the flags for server the certification verification
1525
+ # at the beginning of the SSL/TLS session.
972
1526
  # OpenSSL::SSL::VERIFY_NONE or OpenSSL::SSL::VERIFY_PEER are acceptable.
973
1527
  attr_accessor :verify_mode
974
1528
 
975
- # Sets to check the server certificate is valid for the hostname.
976
- # See OpenSSL::SSL::SSLContext#verify_hostname=
1529
+ # Sets or returns whether to verify that the server certificate is valid
1530
+ # for the hostname.
1531
+ # See {OpenSSL::SSL::SSLContext#verify_hostname=}[https://docs.ruby-lang.org/en/master/OpenSSL/SSL/SSLContext.html#attribute-i-verify_mode].
977
1532
  attr_accessor :verify_hostname
978
1533
 
979
- # Returns the X.509 certificates the server presented.
1534
+ # Returns the X509 certificate chain (an array of strings)
1535
+ # for the session's socket peer,
1536
+ # or +nil+ if none.
980
1537
  def peer_cert
981
1538
  if not use_ssl? or not @socket
982
1539
  return nil
@@ -984,14 +1541,26 @@ module Net #:nodoc:
984
1541
  @socket.io.peer_cert
985
1542
  end
986
1543
 
987
- # Opens a TCP connection and HTTP session.
1544
+ # Starts an \HTTP session.
988
1545
  #
989
- # When this method is called with a block, it passes the Net::HTTP
990
- # object to the block, and closes the TCP connection and HTTP session
991
- # after the block has been executed.
1546
+ # Without a block, returns +self+:
992
1547
  #
993
- # When called with a block, it returns the return value of the
994
- # block; otherwise, it returns self.
1548
+ # http = Net::HTTP.new(hostname)
1549
+ # # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>
1550
+ # http.start
1551
+ # # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=true>
1552
+ # http.started? # => true
1553
+ # http.finish
1554
+ #
1555
+ # With a block, calls the block with +self+,
1556
+ # finishes the session when the block exits,
1557
+ # and returns the block's value:
1558
+ #
1559
+ # http.start do |http|
1560
+ # http
1561
+ # end
1562
+ # # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>
1563
+ # http.started? # => false
995
1564
  #
996
1565
  def start # :yield: http
997
1566
  raise IOError, 'HTTP session already opened' if @started
@@ -1045,8 +1614,8 @@ module Net #:nodoc:
1045
1614
  write_timeout: @write_timeout,
1046
1615
  continue_timeout: @continue_timeout,
1047
1616
  debug_output: @debug_output)
1048
- buf = "CONNECT #{conn_address}:#{@port} HTTP/#{HTTPVersion}\r\n"
1049
- buf << "Host: #{@address}:#{@port}\r\n"
1617
+ buf = +"CONNECT #{conn_address}:#{@port} HTTP/#{HTTPVersion}\r\n" \
1618
+ "Host: #{@address}:#{@port}\r\n"
1050
1619
  if proxy_user
1051
1620
  credential = ["#{proxy_user}:#{proxy_pass}"].pack('m0')
1052
1621
  buf << "Proxy-Authorization: Basic #{credential}\r\n"
@@ -1127,8 +1696,15 @@ module Net #:nodoc:
1127
1696
  end
1128
1697
  private :on_connect
1129
1698
 
1130
- # Finishes the HTTP session and closes the TCP connection.
1131
- # Raises IOError if the session has not been started.
1699
+ # Finishes the \HTTP session:
1700
+ #
1701
+ # http = Net::HTTP.new(hostname)
1702
+ # http.start
1703
+ # http.started? # => true
1704
+ # http.finish # => nil
1705
+ # http.started? # => false
1706
+ #
1707
+ # Raises IOError if not in a session.
1132
1708
  def finish
1133
1709
  raise IOError, 'HTTP session not yet started' unless started?
1134
1710
  do_finish
@@ -1155,12 +1731,12 @@ module Net #:nodoc:
1155
1731
  @proxy_user = nil
1156
1732
  @proxy_pass = nil
1157
1733
 
1158
- # Creates an HTTP proxy class which behaves like Net::HTTP, but
1734
+ # Creates an \HTTP proxy class which behaves like \Net::HTTP, but
1159
1735
  # performs all access via the specified proxy.
1160
1736
  #
1161
1737
  # This class is obsolete. You may pass these same parameters directly to
1162
- # Net::HTTP.new. See Net::HTTP.new for details of the arguments.
1163
- def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil)
1738
+ # \Net::HTTP.new. See Net::HTTP.new for details of the arguments.
1739
+ def HTTP.Proxy(p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil) #:nodoc:
1164
1740
  return self unless p_addr
1165
1741
 
1166
1742
  Class.new(self) {
@@ -1182,31 +1758,37 @@ module Net #:nodoc:
1182
1758
  end
1183
1759
 
1184
1760
  class << HTTP
1185
- # returns true if self is a class which was created by HTTP::Proxy.
1761
+ # Returns true if self is a class which was created by HTTP::Proxy.
1186
1762
  def proxy_class?
1187
1763
  defined?(@is_proxy_class) ? @is_proxy_class : false
1188
1764
  end
1189
1765
 
1190
- # Address of proxy host. If Net::HTTP does not use a proxy, nil.
1766
+ # Returns the address of the proxy host, or +nil+ if none;
1767
+ # see Net::HTTP@Proxy+Server.
1191
1768
  attr_reader :proxy_address
1192
1769
 
1193
- # Port number of proxy host. If Net::HTTP does not use a proxy, nil.
1770
+ # Returns the port number of the proxy host, or +nil+ if none;
1771
+ # see Net::HTTP@Proxy+Server.
1194
1772
  attr_reader :proxy_port
1195
1773
 
1196
- # User name for accessing proxy. If Net::HTTP does not use a proxy, nil.
1774
+ # Returns the user name for accessing the proxy, or +nil+ if none;
1775
+ # see Net::HTTP@Proxy+Server.
1197
1776
  attr_reader :proxy_user
1198
1777
 
1199
- # User password for accessing proxy. If Net::HTTP does not use a proxy,
1200
- # nil.
1778
+ # Returns the password for accessing the proxy, or +nil+ if none;
1779
+ # see Net::HTTP@Proxy+Server.
1201
1780
  attr_reader :proxy_pass
1202
1781
  end
1203
1782
 
1204
- # True if requests for this connection will be proxied
1783
+ # Returns +true+ if a proxy server is defined, +false+ otherwise;
1784
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
1205
1785
  def proxy?
1206
1786
  !!(@proxy_from_env ? proxy_uri : @proxy_address)
1207
1787
  end
1208
1788
 
1209
- # True if the proxy for this connection is determined from the environment
1789
+ # Returns +true+ if the proxy server is defined in the environment,
1790
+ # +false+ otherwise;
1791
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
1210
1792
  def proxy_from_env?
1211
1793
  @proxy_from_env
1212
1794
  end
@@ -1215,12 +1797,13 @@ module Net #:nodoc:
1215
1797
  def proxy_uri # :nodoc:
1216
1798
  return if @proxy_uri == false
1217
1799
  @proxy_uri ||= URI::HTTP.new(
1218
- "http".freeze, nil, address, port, nil, nil, nil, nil, nil
1800
+ "http", nil, address, port, nil, nil, nil, nil, nil
1219
1801
  ).find_proxy || false
1220
1802
  @proxy_uri || nil
1221
1803
  end
1222
1804
 
1223
- # The address of the proxy server, if one is configured.
1805
+ # Returns the address of the proxy server, if defined, +nil+ otherwise;
1806
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
1224
1807
  def proxy_address
1225
1808
  if @proxy_from_env then
1226
1809
  proxy_uri&.hostname
@@ -1229,7 +1812,8 @@ module Net #:nodoc:
1229
1812
  end
1230
1813
  end
1231
1814
 
1232
- # The port of the proxy server, if one is configured.
1815
+ # Returns the port number of the proxy server, if defined, +nil+ otherwise;
1816
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
1233
1817
  def proxy_port
1234
1818
  if @proxy_from_env then
1235
1819
  proxy_uri&.port
@@ -1238,7 +1822,8 @@ module Net #:nodoc:
1238
1822
  end
1239
1823
  end
1240
1824
 
1241
- # The username of the proxy server, if one is configured.
1825
+ # Returns the user name of the proxy server, if defined, +nil+ otherwise;
1826
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
1242
1827
  def proxy_user
1243
1828
  if @proxy_from_env
1244
1829
  user = proxy_uri&.user
@@ -1248,7 +1833,8 @@ module Net #:nodoc:
1248
1833
  end
1249
1834
  end
1250
1835
 
1251
- # The password of the proxy server, if one is configured.
1836
+ # Returns the password of the proxy server, if defined, +nil+ otherwise;
1837
+ # see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
1252
1838
  def proxy_pass
1253
1839
  if @proxy_from_env
1254
1840
  pass = proxy_uri&.password
@@ -1296,45 +1882,38 @@ module Net #:nodoc:
1296
1882
 
1297
1883
  public
1298
1884
 
1299
- # Retrieves data from +path+ on the connected-to host which may be an
1300
- # absolute path String or a URI to extract the path from.
1885
+ # :call-seq:
1886
+ # get(path, initheader = nil) {|res| ... }
1301
1887
  #
1302
- # +initheader+ must be a Hash like { 'Accept' => '*/*', ... },
1303
- # and it defaults to an empty hash.
1304
- # If +initheader+ doesn't have the key 'accept-encoding', then
1305
- # a value of "gzip;q=1.0,deflate;q=0.6,identity;q=0.3" is used,
1306
- # so that gzip compression is used in preference to deflate
1307
- # compression, which is used in preference to no compression.
1308
- # Ruby doesn't have libraries to support the compress (Lempel-Ziv)
1309
- # compression, so that is not supported. The intent of this is
1310
- # to reduce bandwidth by default. If this routine sets up
1311
- # compression, then it does the decompression also, removing
1312
- # the header as well to prevent confusion. Otherwise
1313
- # it leaves the body as it found it.
1888
+ # Sends a GET request to the server;
1889
+ # returns an instance of a subclass of Net::HTTPResponse.
1314
1890
  #
1315
- # This method returns a Net::HTTPResponse object.
1891
+ # The request is based on the Net::HTTP::Get object
1892
+ # created from string +path+ and initial headers hash +initheader+.
1316
1893
  #
1317
- # If called with a block, yields each fragment of the
1318
- # entity body in turn as a string as it is read from
1319
- # the socket. Note that in this case, the returned response
1320
- # object will *not* contain a (meaningful) body.
1894
+ # With a block given, calls the block with the response body:
1321
1895
  #
1322
- # +dest+ argument is obsolete.
1323
- # It still works but you must not use it.
1896
+ # http = Net::HTTP.new(hostname)
1897
+ # http.get('/todos/1') do |res|
1898
+ # p res
1899
+ # end # => #<Net::HTTPOK 200 OK readbody=true>
1900
+ #
1901
+ # Output:
1902
+ #
1903
+ # "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false\n}"
1324
1904
  #
1325
- # This method never raises an exception.
1905
+ # With no block given, simply returns the response object:
1326
1906
  #
1327
- # response = http.get('/index.html')
1907
+ # http.get('/') # => #<Net::HTTPOK 200 OK readbody=true>
1328
1908
  #
1329
- # # using block
1330
- # File.open('result.txt', 'w') {|f|
1331
- # http.get('/~foo/') do |str|
1332
- # f.write str
1333
- # end
1334
- # }
1909
+ # Related:
1910
+ #
1911
+ # - Net::HTTP::Get: request class for \HTTP method GET.
1912
+ # - Net::HTTP.get: sends GET request, returns response body.
1335
1913
  #
1336
1914
  def get(path, initheader = nil, dest = nil, &block) # :yield: +body_segment+
1337
1915
  res = nil
1916
+
1338
1917
  request(Get.new(path, initheader)) {|r|
1339
1918
  r.read_body dest, &block
1340
1919
  res = r
@@ -1342,198 +1921,312 @@ module Net #:nodoc:
1342
1921
  res
1343
1922
  end
1344
1923
 
1345
- # Gets only the header from +path+ on the connected-to host.
1346
- # +header+ is a Hash like { 'Accept' => '*/*', ... }.
1347
- #
1348
- # This method returns a Net::HTTPResponse object.
1924
+ # Sends a HEAD request to the server;
1925
+ # returns an instance of a subclass of Net::HTTPResponse.
1349
1926
  #
1350
- # This method never raises an exception.
1927
+ # The request is based on the Net::HTTP::Head object
1928
+ # created from string +path+ and initial headers hash +initheader+:
1351
1929
  #
1352
- # response = nil
1353
- # Net::HTTP.start('some.www.server', 80) {|http|
1354
- # response = http.head('/index.html')
1355
- # }
1356
- # p response['content-type']
1930
+ # res = http.head('/todos/1') # => #<Net::HTTPOK 200 OK readbody=true>
1931
+ # res.body # => nil
1932
+ # res.to_hash.take(3)
1933
+ # # =>
1934
+ # [["date", ["Wed, 15 Feb 2023 15:25:42 GMT"]],
1935
+ # ["content-type", ["application/json; charset=utf-8"]],
1936
+ # ["connection", ["close"]]]
1357
1937
  #
1358
1938
  def head(path, initheader = nil)
1359
1939
  request(Head.new(path, initheader))
1360
1940
  end
1361
1941
 
1362
- # Posts +data+ (must be a String) to +path+. +header+ must be a Hash
1363
- # like { 'Accept' => '*/*', ... }.
1942
+ # :call-seq:
1943
+ # post(path, data, initheader = nil) {|res| ... }
1944
+ #
1945
+ # Sends a POST request to the server;
1946
+ # returns an instance of a subclass of Net::HTTPResponse.
1364
1947
  #
1365
- # This method returns a Net::HTTPResponse object.
1948
+ # The request is based on the Net::HTTP::Post object
1949
+ # created from string +path+, string +data+, and initial headers hash +initheader+.
1366
1950
  #
1367
- # If called with a block, yields each fragment of the
1368
- # entity body in turn as a string as it is read from
1369
- # the socket. Note that in this case, the returned response
1370
- # object will *not* contain a (meaningful) body.
1951
+ # With a block given, calls the block with the response body:
1371
1952
  #
1372
- # +dest+ argument is obsolete.
1373
- # It still works but you must not use it.
1953
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
1954
+ # http = Net::HTTP.new(hostname)
1955
+ # http.post('/todos', data) do |res|
1956
+ # p res
1957
+ # end # => #<Net::HTTPCreated 201 Created readbody=true>
1374
1958
  #
1375
- # This method never raises exception.
1959
+ # Output:
1376
1960
  #
1377
- # response = http.post('/cgi-bin/search.rb', 'query=foo')
1961
+ # "{\n \"{\\\"userId\\\": 1, \\\"id\\\": 1, \\\"title\\\": \\\"delectus aut autem\\\", \\\"completed\\\": false}\": \"\",\n \"id\": 201\n}"
1378
1962
  #
1379
- # # using block
1380
- # File.open('result.txt', 'w') {|f|
1381
- # http.post('/cgi-bin/search.rb', 'query=foo') do |str|
1382
- # f.write str
1383
- # end
1384
- # }
1963
+ # With no block given, simply returns the response object:
1385
1964
  #
1386
- # You should set Content-Type: header field for POST.
1387
- # If no Content-Type: field given, this method uses
1388
- # "application/x-www-form-urlencoded" by default.
1965
+ # http.post('/todos', data) # => #<Net::HTTPCreated 201 Created readbody=true>
1966
+ #
1967
+ # Related:
1968
+ #
1969
+ # - Net::HTTP::Post: request class for \HTTP method POST.
1970
+ # - Net::HTTP.post: sends POST request, returns response body.
1389
1971
  #
1390
1972
  def post(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
1391
1973
  send_entity(path, data, initheader, dest, Post, &block)
1392
1974
  end
1393
1975
 
1394
- # Sends a PATCH request to the +path+ and gets a response,
1395
- # as an HTTPResponse object.
1976
+ # :call-seq:
1977
+ # patch(path, data, initheader = nil) {|res| ... }
1978
+ #
1979
+ # Sends a PATCH request to the server;
1980
+ # returns an instance of a subclass of Net::HTTPResponse.
1981
+ #
1982
+ # The request is based on the Net::HTTP::Patch object
1983
+ # created from string +path+, string +data+, and initial headers hash +initheader+.
1984
+ #
1985
+ # With a block given, calls the block with the response body:
1986
+ #
1987
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
1988
+ # http = Net::HTTP.new(hostname)
1989
+ # http.patch('/todos/1', data) do |res|
1990
+ # p res
1991
+ # end # => #<Net::HTTPOK 200 OK readbody=true>
1992
+ #
1993
+ # Output:
1994
+ #
1995
+ # "{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"delectus aut autem\",\n \"completed\": false,\n \"{\\\"userId\\\": 1, \\\"id\\\": 1, \\\"title\\\": \\\"delectus aut autem\\\", \\\"completed\\\": false}\": \"\"\n}"
1996
+ #
1997
+ # With no block given, simply returns the response object:
1998
+ #
1999
+ # http.patch('/todos/1', data) # => #<Net::HTTPCreated 201 Created readbody=true>
2000
+ #
1396
2001
  def patch(path, data, initheader = nil, dest = nil, &block) # :yield: +body_segment+
1397
2002
  send_entity(path, data, initheader, dest, Patch, &block)
1398
2003
  end
1399
2004
 
1400
- def put(path, data, initheader = nil) #:nodoc:
2005
+ # Sends a PUT request to the server;
2006
+ # returns an instance of a subclass of Net::HTTPResponse.
2007
+ #
2008
+ # The request is based on the Net::HTTP::Put object
2009
+ # created from string +path+, string +data+, and initial headers hash +initheader+.
2010
+ #
2011
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
2012
+ # http = Net::HTTP.new(hostname)
2013
+ # http.put('/todos/1', data) # => #<Net::HTTPOK 200 OK readbody=true>
2014
+ #
2015
+ def put(path, data, initheader = nil)
1401
2016
  request(Put.new(path, initheader), data)
1402
2017
  end
1403
2018
 
1404
- # Sends a PROPPATCH request to the +path+ and gets a response,
1405
- # as an HTTPResponse object.
2019
+ # Sends a PROPPATCH request to the server;
2020
+ # returns an instance of a subclass of Net::HTTPResponse.
2021
+ #
2022
+ # The request is based on the Net::HTTP::Proppatch object
2023
+ # created from string +path+, string +body+, and initial headers hash +initheader+.
2024
+ #
2025
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
2026
+ # http = Net::HTTP.new(hostname)
2027
+ # http.proppatch('/todos/1', data)
2028
+ #
1406
2029
  def proppatch(path, body, initheader = nil)
1407
2030
  request(Proppatch.new(path, initheader), body)
1408
2031
  end
1409
2032
 
1410
- # Sends a LOCK request to the +path+ and gets a response,
1411
- # as an HTTPResponse object.
2033
+ # Sends a LOCK request to the server;
2034
+ # returns an instance of a subclass of Net::HTTPResponse.
2035
+ #
2036
+ # The request is based on the Net::HTTP::Lock object
2037
+ # created from string +path+, string +body+, and initial headers hash +initheader+.
2038
+ #
2039
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
2040
+ # http = Net::HTTP.new(hostname)
2041
+ # http.lock('/todos/1', data)
2042
+ #
1412
2043
  def lock(path, body, initheader = nil)
1413
2044
  request(Lock.new(path, initheader), body)
1414
2045
  end
1415
2046
 
1416
- # Sends a UNLOCK request to the +path+ and gets a response,
1417
- # as an HTTPResponse object.
2047
+ # Sends an UNLOCK request to the server;
2048
+ # returns an instance of a subclass of Net::HTTPResponse.
2049
+ #
2050
+ # The request is based on the Net::HTTP::Unlock object
2051
+ # created from string +path+, string +body+, and initial headers hash +initheader+.
2052
+ #
2053
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
2054
+ # http = Net::HTTP.new(hostname)
2055
+ # http.unlock('/todos/1', data)
2056
+ #
1418
2057
  def unlock(path, body, initheader = nil)
1419
2058
  request(Unlock.new(path, initheader), body)
1420
2059
  end
1421
2060
 
1422
- # Sends a OPTIONS request to the +path+ and gets a response,
1423
- # as an HTTPResponse object.
2061
+ # Sends an Options request to the server;
2062
+ # returns an instance of a subclass of Net::HTTPResponse.
2063
+ #
2064
+ # The request is based on the Net::HTTP::Options object
2065
+ # created from string +path+ and initial headers hash +initheader+.
2066
+ #
2067
+ # http = Net::HTTP.new(hostname)
2068
+ # http.options('/')
2069
+ #
1424
2070
  def options(path, initheader = nil)
1425
2071
  request(Options.new(path, initheader))
1426
2072
  end
1427
2073
 
1428
- # Sends a PROPFIND request to the +path+ and gets a response,
1429
- # as an HTTPResponse object.
2074
+ # Sends a PROPFIND request to the server;
2075
+ # returns an instance of a subclass of Net::HTTPResponse.
2076
+ #
2077
+ # The request is based on the Net::HTTP::Propfind object
2078
+ # created from string +path+, string +body+, and initial headers hash +initheader+.
2079
+ #
2080
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
2081
+ # http = Net::HTTP.new(hostname)
2082
+ # http.propfind('/todos/1', data)
2083
+ #
1430
2084
  def propfind(path, body = nil, initheader = {'Depth' => '0'})
1431
2085
  request(Propfind.new(path, initheader), body)
1432
2086
  end
1433
2087
 
1434
- # Sends a DELETE request to the +path+ and gets a response,
1435
- # as an HTTPResponse object.
2088
+ # Sends a DELETE request to the server;
2089
+ # returns an instance of a subclass of Net::HTTPResponse.
2090
+ #
2091
+ # The request is based on the Net::HTTP::Delete object
2092
+ # created from string +path+ and initial headers hash +initheader+.
2093
+ #
2094
+ # http = Net::HTTP.new(hostname)
2095
+ # http.delete('/todos/1')
2096
+ #
1436
2097
  def delete(path, initheader = {'Depth' => 'Infinity'})
1437
2098
  request(Delete.new(path, initheader))
1438
2099
  end
1439
2100
 
1440
- # Sends a MOVE request to the +path+ and gets a response,
1441
- # as an HTTPResponse object.
2101
+ # Sends a MOVE request to the server;
2102
+ # returns an instance of a subclass of Net::HTTPResponse.
2103
+ #
2104
+ # The request is based on the Net::HTTP::Move object
2105
+ # created from string +path+ and initial headers hash +initheader+.
2106
+ #
2107
+ # http = Net::HTTP.new(hostname)
2108
+ # http.move('/todos/1')
2109
+ #
1442
2110
  def move(path, initheader = nil)
1443
2111
  request(Move.new(path, initheader))
1444
2112
  end
1445
2113
 
1446
- # Sends a COPY request to the +path+ and gets a response,
1447
- # as an HTTPResponse object.
2114
+ # Sends a COPY request to the server;
2115
+ # returns an instance of a subclass of Net::HTTPResponse.
2116
+ #
2117
+ # The request is based on the Net::HTTP::Copy object
2118
+ # created from string +path+ and initial headers hash +initheader+.
2119
+ #
2120
+ # http = Net::HTTP.new(hostname)
2121
+ # http.copy('/todos/1')
2122
+ #
1448
2123
  def copy(path, initheader = nil)
1449
2124
  request(Copy.new(path, initheader))
1450
2125
  end
1451
2126
 
1452
- # Sends a MKCOL request to the +path+ and gets a response,
1453
- # as an HTTPResponse object.
2127
+ # Sends a MKCOL request to the server;
2128
+ # returns an instance of a subclass of Net::HTTPResponse.
2129
+ #
2130
+ # The request is based on the Net::HTTP::Mkcol object
2131
+ # created from string +path+, string +body+, and initial headers hash +initheader+.
2132
+ #
2133
+ # data = '{"userId": 1, "id": 1, "title": "delectus aut autem", "completed": false}'
2134
+ # http.mkcol('/todos/1', data)
2135
+ # http = Net::HTTP.new(hostname)
2136
+ #
1454
2137
  def mkcol(path, body = nil, initheader = nil)
1455
2138
  request(Mkcol.new(path, initheader), body)
1456
2139
  end
1457
2140
 
1458
- # Sends a TRACE request to the +path+ and gets a response,
1459
- # as an HTTPResponse object.
2141
+ # Sends a TRACE request to the server;
2142
+ # returns an instance of a subclass of Net::HTTPResponse.
2143
+ #
2144
+ # The request is based on the Net::HTTP::Trace object
2145
+ # created from string +path+ and initial headers hash +initheader+.
2146
+ #
2147
+ # http = Net::HTTP.new(hostname)
2148
+ # http.trace('/todos/1')
2149
+ #
1460
2150
  def trace(path, initheader = nil)
1461
2151
  request(Trace.new(path, initheader))
1462
2152
  end
1463
2153
 
1464
- # Sends a GET request to the +path+.
1465
- # Returns the response as a Net::HTTPResponse object.
2154
+ # Sends a GET request to the server;
2155
+ # forms the response into a Net::HTTPResponse object.
2156
+ #
2157
+ # The request is based on the Net::HTTP::Get object
2158
+ # created from string +path+ and initial headers hash +initheader+.
1466
2159
  #
1467
- # When called with a block, passes an HTTPResponse object to the block.
1468
- # The body of the response will not have been read yet;
1469
- # the block can process it using HTTPResponse#read_body,
1470
- # if desired.
2160
+ # With no block given, returns the response object:
1471
2161
  #
1472
- # Returns the response.
2162
+ # http = Net::HTTP.new(hostname)
2163
+ # http.request_get('/todos') # => #<Net::HTTPOK 200 OK readbody=true>
2164
+ #
2165
+ # With a block given, calls the block with the response object
2166
+ # and returns the response object:
1473
2167
  #
1474
- # This method never raises Net::* exceptions.
2168
+ # http.request_get('/todos') do |res|
2169
+ # p res
2170
+ # end # => #<Net::HTTPOK 200 OK readbody=true>
1475
2171
  #
1476
- # response = http.request_get('/index.html')
1477
- # # The entity body is already read in this case.
1478
- # p response['content-type']
1479
- # puts response.body
2172
+ # Output:
1480
2173
  #
1481
- # # Using a block
1482
- # http.request_get('/index.html') {|response|
1483
- # p response['content-type']
1484
- # response.read_body do |str| # read body now
1485
- # print str
1486
- # end
1487
- # }
2174
+ # #<Net::HTTPOK 200 OK readbody=false>
1488
2175
  #
1489
2176
  def request_get(path, initheader = nil, &block) # :yield: +response+
1490
2177
  request(Get.new(path, initheader), &block)
1491
2178
  end
1492
2179
 
1493
- # Sends a HEAD request to the +path+ and returns the response
1494
- # as a Net::HTTPResponse object.
1495
- #
1496
- # Returns the response.
2180
+ # Sends a HEAD request to the server;
2181
+ # returns an instance of a subclass of Net::HTTPResponse.
1497
2182
  #
1498
- # This method never raises Net::* exceptions.
2183
+ # The request is based on the Net::HTTP::Head object
2184
+ # created from string +path+ and initial headers hash +initheader+.
1499
2185
  #
1500
- # response = http.request_head('/index.html')
1501
- # p response['content-type']
2186
+ # http = Net::HTTP.new(hostname)
2187
+ # http.head('/todos/1') # => #<Net::HTTPOK 200 OK readbody=true>
1502
2188
  #
1503
2189
  def request_head(path, initheader = nil, &block)
1504
2190
  request(Head.new(path, initheader), &block)
1505
2191
  end
1506
2192
 
1507
- # Sends a POST request to the +path+.
2193
+ # Sends a POST request to the server;
2194
+ # forms the response into a Net::HTTPResponse object.
2195
+ #
2196
+ # The request is based on the Net::HTTP::Post object
2197
+ # created from string +path+, string +data+, and initial headers hash +initheader+.
1508
2198
  #
1509
- # Returns the response as a Net::HTTPResponse object.
2199
+ # With no block given, returns the response object:
1510
2200
  #
1511
- # When called with a block, the block is passed an HTTPResponse
1512
- # object. The body of that response will not have been read yet;
1513
- # the block can process it using HTTPResponse#read_body, if desired.
2201
+ # http = Net::HTTP.new(hostname)
2202
+ # http.post('/todos', 'xyzzy')
2203
+ # # => #<Net::HTTPCreated 201 Created readbody=true>
1514
2204
  #
1515
- # Returns the response.
2205
+ # With a block given, calls the block with the response body
2206
+ # and returns the response object:
1516
2207
  #
1517
- # This method never raises Net::* exceptions.
2208
+ # http.post('/todos', 'xyzzy') do |res|
2209
+ # p res
2210
+ # end # => #<Net::HTTPCreated 201 Created readbody=true>
1518
2211
  #
1519
- # # example
1520
- # response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
1521
- # p response.status
1522
- # puts response.body # body is already read in this case
2212
+ # Output:
1523
2213
  #
1524
- # # using block
1525
- # http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
1526
- # p response.status
1527
- # p response['content-type']
1528
- # response.read_body do |str| # read body now
1529
- # print str
1530
- # end
1531
- # }
2214
+ # "{\n \"xyzzy\": \"\",\n \"id\": 201\n}"
1532
2215
  #
1533
2216
  def request_post(path, data, initheader = nil, &block) # :yield: +response+
1534
2217
  request Post.new(path, initheader), data, &block
1535
2218
  end
1536
2219
 
2220
+ # Sends a PUT request to the server;
2221
+ # returns an instance of a subclass of Net::HTTPResponse.
2222
+ #
2223
+ # The request is based on the Net::HTTP::Put object
2224
+ # created from string +path+, string +data+, and initial headers hash +initheader+.
2225
+ #
2226
+ # http = Net::HTTP.new(hostname)
2227
+ # http.put('/todos/1', 'xyzzy')
2228
+ # # => #<Net::HTTPOK 200 OK readbody=true>
2229
+ #
1537
2230
  def request_put(path, data, initheader = nil, &block) #:nodoc:
1538
2231
  request Put.new(path, initheader), data, &block
1539
2232
  end
@@ -1543,16 +2236,25 @@ module Net #:nodoc:
1543
2236
  alias post2 request_post #:nodoc: obsolete
1544
2237
  alias put2 request_put #:nodoc: obsolete
1545
2238
 
1546
-
1547
- # Sends an HTTP request to the HTTP server.
1548
- # Also sends a DATA string if +data+ is given.
2239
+ # Sends an \HTTP request to the server;
2240
+ # returns an instance of a subclass of Net::HTTPResponse.
1549
2241
  #
1550
- # Returns a Net::HTTPResponse object.
2242
+ # The request is based on the Net::HTTPRequest object
2243
+ # created from string +path+, string +data+, and initial headers hash +header+.
2244
+ # That object is an instance of the
2245
+ # {subclass of Net::HTTPRequest}[rdoc-ref:Net::HTTPRequest@Request+Subclasses],
2246
+ # that corresponds to the given uppercase string +name+,
2247
+ # which must be
2248
+ # an {HTTP request method}[https://en.wikipedia.org/wiki/HTTP#Request_methods]
2249
+ # or a {WebDAV request method}[https://en.wikipedia.org/wiki/WebDAV#Implementation].
1551
2250
  #
1552
- # This method never raises Net::* exceptions.
2251
+ # Examples:
1553
2252
  #
1554
- # response = http.send_request('GET', '/index.html')
1555
- # puts response.body
2253
+ # http = Net::HTTP.new(hostname)
2254
+ # http.send_request('GET', '/todos/1')
2255
+ # # => #<Net::HTTPOK 200 OK readbody=true>
2256
+ # http.send_request('POST', '/todos', 'xyzzy')
2257
+ # # => #<Net::HTTPCreated 201 Created readbody=true>
1556
2258
  #
1557
2259
  def send_request(name, path, data = nil, header = nil)
1558
2260
  has_response_body = name != 'HEAD'
@@ -1560,20 +2262,35 @@ module Net #:nodoc:
1560
2262
  request r, data
1561
2263
  end
1562
2264
 
1563
- # Sends an HTTPRequest object +req+ to the HTTP server.
2265
+ # Sends the given request +req+ to the server;
2266
+ # forms the response into a Net::HTTPResponse object.
1564
2267
  #
1565
- # If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing
1566
- # data, the data is also sent. Providing data for a Net::HTTP::Head or
1567
- # Net::HTTP::Get request results in an ArgumentError.
2268
+ # The given +req+ must be an instance of a
2269
+ # {subclass of Net::HTTPRequest}[rdoc-ref:Net::HTTPRequest@Request+Subclasses].
2270
+ # Argument +body+ should be given only if needed for the request.
1568
2271
  #
1569
- # Returns an HTTPResponse object.
2272
+ # With no block given, returns the response object:
1570
2273
  #
1571
- # When called with a block, passes an HTTPResponse object to the block.
1572
- # The body of the response will not have been read yet;
1573
- # the block can process it using HTTPResponse#read_body,
1574
- # if desired.
2274
+ # http = Net::HTTP.new(hostname)
2275
+ #
2276
+ # req = Net::HTTP::Get.new('/todos/1')
2277
+ # http.request(req)
2278
+ # # => #<Net::HTTPOK 200 OK readbody=true>
2279
+ #
2280
+ # req = Net::HTTP::Post.new('/todos')
2281
+ # http.request(req, 'xyzzy')
2282
+ # # => #<Net::HTTPCreated 201 Created readbody=true>
2283
+ #
2284
+ # With a block given, calls the block with the response and returns the response:
2285
+ #
2286
+ # req = Net::HTTP::Get.new('/todos/1')
2287
+ # http.request(req) do |res|
2288
+ # p res
2289
+ # end # => #<Net::HTTPOK 200 OK readbody=true>
2290
+ #
2291
+ # Output:
1575
2292
  #
1576
- # This method never raises Net::* exceptions.
2293
+ # #<Net::HTTPOK 200 OK readbody=false>
1577
2294
  #
1578
2295
  def request(req, body = nil, &block) # :yield: +response+
1579
2296
  unless started?