Project

General

Profile

Feature #4100 ยป net-http-2010.patch

Patches against 1.9 HEAD to improve net/http documentation - meta (mathew murphy), 11/30/2010 08:26 AM

View differences:

http.rb (working copy)
97 97
  #                               {'q' => 'ruby', 'max' => '50'})
98 98
  #     puts res.body
99 99
  #
100
  #     #2: POST with basic authentication
100
  #     #2: POST with basic authentication supplied in the URL
101
  #
102
  #     (Note that this is not a legal URL as per RFC 1738 section 3.3, but 
103
  #     is supported by post_form for historical reasons.)
104
  #
101 105
  #     res = Net::HTTP.post_form(URI.parse('http://jack:pass@www.example.com/todo.cgi'),
102 106
  #                                         {'from' => '2005-01-01',
103 107
  #                                          'to' => '2005-03-31'})
104 108
  #     puts res.body
105 109
  #
106
  #     #3: Detailed control
110
  #     #3: Detailed control of POST with authentication
111
  #
107 112
  #     uri = URI.parse('http://www.example.com/todo.cgi')
108 113
  #     req = Net::HTTP::Post.new(uri.path)
109 114
  #     req.basic_auth 'jack', 'pass'
......
123 128
  #
124 129
  # === Accessing via Proxy
125 130
  #
126
  # Net::HTTP::Proxy has the same methods as Net::HTTP but its instances always
127
  # connect via the proxy, instead of given host.
131
  # Net::HTTP.Proxy is an http proxy class. It has the same
132
  # methods as Net::HTTP, but its instances always connect via a proxy,
133
  # instead of directly to the given host.
128 134
  #
129 135
  #     require 'net/http'
130 136
  #
......
136 142
  #             :
137 143
  #     }
138 144
  #
139
  # Since Net::HTTP::Proxy returns Net::HTTP itself when proxy_addr is nil,
140
  # there's no need to change code if there's a proxy or not.
145
  # The top-level Net::HTTP class creates objects which represent
146
  # HTTP sessions.
141 147
  #
142
  # There are two additional parameters in Net::HTTP::Proxy which you can use to
143
  # specify a proxy username and password:
148
  # Since Net::HTTP.Proxy returns Net::HTTP itself when +proxy_addr+ is nil,
149
  # there's no need to change your code depending on whether there's a proxy 
150
  # or not.
151
  # 
152
  # There are two additional parameters in Net::HTTP.Proxy which allow you to
153
  # specify a user name and password for the proxy:
144 154
  #
145 155
  #     Net::HTTP::Proxy(proxy_addr, proxy_port, proxy_user = nil, proxy_pass = nil)
146 156
  #
147
  # You may use them to work with authorization-enabled proxies:
157
  # You can use them to work with authorization-enabled proxies:
148 158
  #
149 159
  #     require 'net/http'
150 160
  #     require 'uri'
......
160 170
  #     }
161 171
  #
162 172
  # Note that net/http does not use the HTTP_PROXY environment variable.
163
  # If you want to use a proxy, you must set it explicitly.
173
  # If you want to use a proxy, you must do so explicitly.
164 174
  #
165 175
  # === Following Redirection
166 176
  #
......
183 193
  #     print fetch('http://www.ruby-lang.org')
184 194
  #
185 195
  # Net::HTTPSuccess and Net::HTTPRedirection are HTTPResponse subclasses.
186
  # All HTTPResponse objects belong to their own response class which
187
  # indicates the HTTP result status.
196
  # All HTTPResponse objects belong to their own response class, which
197
  # indicates the HTTP result status. For details of the response classes,
198
  # see the section "HTTP Response Classes".
188 199
  #
200
  # === Full example with retrying and error reporting
201
  #
202
  #     require 'uri'
203
  #     require 'net/http'
204
  #     
205
  #     url = "http://www.example.com/"
206
  #     
207
  #     # Break apart the URL
208
  #     uri = URI.parse(url)
209
  #     # Reassemble the path for the HTTP request
210
  #     if uri.query
211
  #       path = uri.path + '?' + uri.query
212
  #     else
213
  #       path = uri.path
214
  #     end
215
  #     
216
  #     # Create a request object
217
  #     request = Net::HTTP::Get.new(path)
218
  #     
219
  #     # Prepare an HTTP connection object
220
  #     http = Net::HTTP.new(uri.host, uri.port)
221
  #     
222
  #     # Open the connection and issue the request, retrying up to 3 times if there
223
  #     # is a timeout
224
  #     attempts = 1
225
  #     begin
226
  #       response = http.request(request)
227
  #     rescue Exception => e
228
  #       puts e
229
  #       puts "[Retrying]"
230
  #       attempts += 1
231
  #       retry if attempts <= 3
232
  #     end
233
  #     
234
  #     # Report the result
235
  #     if response.kind_of? Net::HTTPSuccess
236
  #       puts response.body
237
  #     else
238
  #       raise "Error fetching #{url}: #{response.code} #{response.message}"
239
  #     end
240
  #
189 241
  # === HTTP Request Classes
190 242
  #
191 243
  # Here is HTTP request class hierarchy.
......
208 260
  #
209 261
  # === HTTP Response Classes
210 262
  #
211
  # Here is HTTP response class hierarchy.
212
  # All classes are defined in Net module.
263
  # The request() method returns a response of a specific class, depending
264
  # on the result of the HTTP request.
213 265
  #
214
  #   HTTPResponse
215
  #       HTTPUnknownResponse
216
  #       HTTPInformation                    # 1xx
217
  #           HTTPContinue                       # 100
218
  #           HTTPSwitchProtocol                 # 101
219
  #       HTTPSuccess                        # 2xx
220
  #           HTTPOK                             # 200
221
  #           HTTPCreated                        # 201
222
  #           HTTPAccepted                       # 202
223
  #           HTTPNonAuthoritativeInformation    # 203
224
  #           HTTPNoContent                      # 204
225
  #           HTTPResetContent                   # 205
226
  #           HTTPPartialContent                 # 206
227
  #       HTTPRedirection                    # 3xx
228
  #           HTTPMultipleChoice                 # 300
229
  #           HTTPMovedPermanently               # 301
230
  #           HTTPFound                          # 302
231
  #           HTTPSeeOther                       # 303
232
  #           HTTPNotModified                    # 304
233
  #           HTTPUseProxy                       # 305
234
  #           HTTPTemporaryRedirect              # 307
235
  #       HTTPClientError                    # 4xx
236
  #           HTTPBadRequest                     # 400
237
  #           HTTPUnauthorized                   # 401
238
  #           HTTPPaymentRequired                # 402
239
  #           HTTPForbidden                      # 403
240
  #           HTTPNotFound                       # 404
241
  #           HTTPMethodNotAllowed               # 405
242
  #           HTTPNotAcceptable                  # 406
243
  #           HTTPProxyAuthenticationRequired    # 407
244
  #           HTTPRequestTimeOut                 # 408
245
  #           HTTPConflict                       # 409
246
  #           HTTPGone                           # 410
247
  #           HTTPLengthRequired                 # 411
248
  #           HTTPPreconditionFailed             # 412
249
  #           HTTPRequestEntityTooLarge          # 413
250
  #           HTTPRequestURITooLong              # 414
251
  #           HTTPUnsupportedMediaType           # 415
252
  #           HTTPRequestedRangeNotSatisfiable   # 416
253
  #           HTTPExpectationFailed              # 417
254
  #       HTTPServerError                    # 5xx
255
  #           HTTPInternalServerError            # 500
256
  #           HTTPNotImplemented                 # 501
257
  #           HTTPBadGateway                     # 502
258
  #           HTTPServiceUnavailable             # 503
259
  #           HTTPGatewayTimeOut                 # 504
260
  #           HTTPVersionNotSupported            # 505
266
  # To check the result, you can use the kind_of? method. Example:
261 267
  #
268
  #     response = http.request(req)
269
  #     case
270
  #       when response.kind_of? Net::HTTPSuccess
271
  #         # Succeeded
272
  #       when response.kind_of? Net::HTTPRedirection
273
  #         # Page has moved, handle redirect
274
  #       when response.kind_of? Net::HTTPServerError
275
  #         # Site is broken
276
  #     end
277
  #
278
  # See Net::HTTPResponse for the complete hierarchy of response classes.
279
  #
280
  # The HTTPResponse classes all provide +code+ and +message+ accessors to 
281
  # obtain the 3-digit HTTP result code and the HTTP result message sent by 
282
  # the server.
283
  #
262 284
  # == Switching Net::HTTP versions
263 285
  #
264 286
  # You can use net/http.rb 1.1 features (bundled with Ruby 1.6)
......
294 316
    # Turns on net/http 1.2 (ruby 1.8) features.
295 317
    # Defaults to ON in ruby 1.8.
296 318
    #
297
    # I strongly recommend to call this method always.
319
    # It is strongly recommend that you call this method always, unless
320
    # you have a specific reason for needing only HTTP 1.1.
298 321
    #
299 322
    #   require 'net/http'
300 323
    #   Net::HTTP.version_1_2
......
309 332
      @newimpl = false
310 333
    end
311 334

  
312
    # true if net/http is in version 1.2 mode.
335
    # Returns true if net/http is in version 1.2 mode.
313 336
    # Defaults to true.
314 337
    def HTTP.version_1_2?
315 338
      @newimpl
316 339
    end
317 340

  
318
    # true if net/http is in version 1.1 compatible mode.
341
!   # Returns true if net/http is in version 1.1 compatible mode.
319 342
    # Defaults to true.
320 343
    def HTTP.version_1_1?
321 344
      not @newimpl
......
331 354
    #
332 355

  
333 356
    #
334
    # Get body from target and output it to +$stdout+.  The
335
    # target can either be specified as (+uri+), or as
336
    # (+host+, +path+, +port+ = 80); so:
357
    # Gets the body text from the target and outputs it to $stdout.  The
358
    # target can either be specified as a URI object, or as
359
    # (host, path, port = 80); so: 
337 360
    #
338 361
    #    Net::HTTP.get_print URI.parse('http://www.example.com/index.html')
339 362
    #
......
350 373
      nil
351 374
    end
352 375

  
353
    # Send a GET request to the target and return the response
376
    # Sends a GET request to the target and returns the HTTP response
354 377
    # as a string.  The target can either be specified as
355 378
    # (+uri+), or as (+host+, +path+, +port+ = 80); so:
356 379
    #
......
364 387
      get_response(uri_or_host, path, port).body
365 388
    end
366 389

  
367
    # Send a GET request to the target and return the response
390
    # Sends a GET request to the target and returns the HTTP response
368 391
    # as a Net::HTTPResponse object.  The target can either be specified as
369 392
    # (+uri+), or as (+host+, +path+, +port+ = 80); so:
370 393
    #
......
390 413
      end
391 414
    end
392 415

  
393
    # Posts HTML form data to the +URL+.
394
    # Form data must be represented as a Hash of String to String, e.g:
416
    # Posts HTML form data to the specified URI object.
417
    # The form data must be provided as a Hash mapping from String to String.
418
    # Example:
395 419
    #
396 420
    #   { "cmd" => "search", "q" => "ruby", "max" => "50" }
397 421
    #
398
    # This method also does Basic Authentication iff +URL+.user exists.
422
    # This method also does Basic Authentication iff +URI+.user exists.
399 423
    #
400 424
    # Example:
401 425
    #
......
441 465
    #   HTTP.start(address, port, p_addr, p_port, p_user, p_pass, &block)
442 466
    #   HTTP.start(address, port=nil, p_addr=nil, p_port=nil, p_user=nil, p_pass=nil, opt, &block)
443 467
    #
444
    # creates a new Net::HTTP object and opens its TCP connection and
445
    # HTTP session.
468
    # Creates a new Net::HTTP object, then additionally opens the TCP
469
    # connection and HTTP session.
446 470
    #
447 471
    # Argments are following:
448 472
    # _address_ :: hostname or IP address of the server
......
465 489
    # block finishes.  In this case, the return value of this method
466 490
    # is the return value of the block.  If no block is given, the
467 491
    # return value of this method is the newly created Net::HTTP object
468
    # itself, and the caller is responsible for closing it upon completion.
492
    # itself, and the caller is responsible for closing it upon completion
493
    # using the finish() method.
469 494
    def HTTP.start(address, *arg, &block) # :yield: +http+
470 495
      arg.pop if opt = Hash.try_convert(arg[-1])
471 496
      port, p_addr, p_port, p_user, p_pass = *arg
......
488 513
      alias newobj new
489 514
    end
490 515

  
491
    # Creates a new Net::HTTP object.
492
    # If +proxy_addr+ is given, creates an Net::HTTP object with proxy support.
493
    # This method does not open the TCP connection.
516
    # Creates a new Net::HTTP object without opening a TCP connection or
517
    # HTTP session.
518
    # The +address+ should be a DNS hostname or IP address.
519
    # If +p_addr+ is given, creates a Net::HTTP object with proxy support.
494 520
    def HTTP.new(address, port = nil, p_addr = nil, p_port = nil, p_user = nil, p_pass = nil)
495 521
      h = Proxy(p_addr, p_port, p_user, p_pass).newobj(address, port)
496 522
      h.instance_eval {
......
499 525
      h
500 526
    end
501 527

  
502
    # Creates a new Net::HTTP object for the specified +address+.
503
    # This method does not open the TCP connection.
528
    # Creates a new Net::HTTP object for the specified server address,
529
    # without opening the TCP connection or initializing the HTTP session.
530
    # The +address+ should be a DNS hostname or IP address.
504 531
    def initialize(address, port = nil)
505 532
      @address = address
506 533
      @port    = (port || HTTP.default_port)
......
528 555
      "#<#{self.class} #{@address}:#{@port} open=#{started?}>"
529 556
    end
530 557

  
531
    # *WARNING* This method causes serious security hole.
558
    # *WARNING* This method opens a serious security hole.
532 559
    # Never use this method in production code.
533 560
    #
534
    # Set an output stream for debugging.
561
    # Sets an output stream for debugging.
535 562
    #
536 563
    #   http = Net::HTTP.new
537 564
    #   http.set_debug_output $stderr
......
542 569
      @debug_output = output
543 570
    end
544 571

  
545
    # The host name to connect to.
572
    # The DNS host name or IP address to connect to.
546 573
    attr_reader :address
547 574

  
548 575
    # The port number to connect to.
549 576
    attr_reader :port
550 577

  
551
    # Seconds to wait until connection is opened.
578
    # Number of seconds to wait for the connection to open.
552 579
    # If the HTTP object cannot open a connection in this many seconds,
553 580
    # it raises a TimeoutError exception.
554 581
    attr_accessor :open_timeout
555 582

  
556
    # Seconds to wait until reading one block (by one read(2) call).
557
    # If the HTTP object cannot open a connection in this many seconds,
583
    # Number of seconds to wait for one block to be read (via one read(2)
584
    # call). If the HTTP object cannot read data in this many seconds,
558 585
    # it raises a TimeoutError exception.
559 586
    attr_reader :read_timeout
560 587

  
......
564 591
      @read_timeout = sec
565 592
    end
566 593

  
567
    # returns true if the HTTP session is started.
594
    # Returns true if the HTTP session has been started.
568 595
    def started?
569 596
      @started
570 597
    end
......
573 600

  
574 601
    attr_accessor :close_on_empty_response
575 602

  
576
    # returns true if use SSL/TLS with HTTP.
603
    # Returns true if SSL/TLS is being used with HTTP.
577 604
    def use_ssl?
578 605
      @use_ssl
579 606
    end
......
604 631
      @socket.io.peer_cert
605 632
    end
606 633

  
607
    # Opens TCP connection and HTTP session.
634
    # Opens a TCP connection and HTTP session.
635
    # 
636
    # When this method is called with a block, it passes the Net::HTTP 
637
    # object to the block, and closes the TCP connection and HTTP session
638
    # after the block has been executed.
608 639
    #
609
    # When this method is called with block, gives a HTTP object
610
    # to the block and closes the TCP connection / HTTP session
611
    # after the block executed.
640
    # When called with a block, it returns the return value of the
641
    # block; otherwise, it returns self.
612 642
    #
613
    # When called with a block, returns the return value of the
614
    # block; otherwise, returns self.
615
    #
616 643
    def start  # :yield: http
617 644
      raise IOError, 'HTTP session already opened' if @started
618 645
      if block_given?
......
681 708
    end
682 709
    private :on_connect
683 710

  
684
    # Finishes HTTP session and closes TCP connection.
685
    # Raises IOError if not started.
711
    # Finishes the HTTP session and closes the TCP connection.
712
    # Raises IOError if the session has not been started.
686 713
    def finish
687 714
      raise IOError, 'HTTP session not yet started' unless started?
688 715
      do_finish
......
708 735
    @proxy_user = nil
709 736
    @proxy_pass = nil
710 737

  
711
    # Creates an HTTP proxy class.
712
    # Arguments are address/port of proxy host and username/password
713
    # if authorization on proxy server is required.
714
    # You can replace the HTTP class with created proxy class.
738
    # Creates an HTTP proxy class which behaves like Net::HTTP, but
739
    # performs all access via the specified proxy.
715 740
    #
716
    # If ADDRESS is nil, this method returns self (Net::HTTP).
741
    # The arguments are the DNS name or IP address of the proxy host,
742
    # the port to use to access the proxy, and a username and password
743
    # if authorization is required to use the proxy.
717 744
    #
745
    # You can replace any use of the Net::HTTP class with use of the
746
    # proxy class created.
747
    # 
748
    # If +p_addr+ is nil, this method returns self (a Net::HTTP object).
749
    #
718 750
    #     # Example
719 751
    #     proxy_class = Net::HTTP::Proxy('proxy.example.com', 8080)
720 752
    #                     :
......
846 878
    #
847 879
    # In version 1.1, this method might raise an exception for
848 880
    # 3xx (redirect). In this case you can get a HTTPResponse object
849
    # by "anException.response".
881
    # from "anException.response".
850 882
    #
851
    # In version 1.2, this method never raises exception.
883
    # In version 1.2, this method never raises an exception.
852 884
    #
853 885
    #     # version 1.1 (bundled with Ruby 1.6)
854 886
    #     response, body = http.get('/index.html')
......
907 939
    #
908 940
    # In version 1.1, this method might raise an exception for
909 941
    # 3xx (redirect). On the case you can get a HTTPResponse object
910
    # by "anException.response".
942
    # as "anException.response".
943
    #
911 944
    # In version 1.2, this method never raises an exception.
912 945
    #
913 946
    #     response = nil
......
930 963
    # In version 1.2 (ruby 1.8), this method returns a Net::HTTPResponse object.
931 964
    #
932 965
    # If called with a block, yields each fragment of the
933
    # entity body in turn as a string as it are read from
966
    # entity body in turn as a string as it is read from
934 967
    # the socket.  Note that in this case, the returned response
935 968
    # object will *not* contain a (meaningful) body.
936 969
    #
......
1035 1068
      request(Trace.new(path, initheader))
1036 1069
    end
1037 1070

  
1038
    # Sends a GET request to the +path+ and gets a response,
1039
    # as an HTTPResponse object.
1071
    # Sends a GET request to the +path+.
1072
    # Returns the response as a Net::HTTPResponse object.
1040 1073
    #
1041
    # When called with a block, yields an HTTPResponse object.
1042
    # The body of this response will not have been read yet;
1043
    # the caller can process it using HTTPResponse#read_body,
1074
    # When called with a block, passes an HTTPResponse object to the block.
1075
    # The body of the response will not have been read yet;
1076
    # the block can process it using HTTPResponse#read_body,
1044 1077
    # if desired.
1045 1078
    #
1046 1079
    # Returns the response.
......
1048 1081
    # This method never raises Net::* exceptions.
1049 1082
    #
1050 1083
    #     response = http.request_get('/index.html')
1051
    #     # The entity body is already read here.
1084
    #     # The entity body is already read in this case.
1052 1085
    #     p response['content-type']
1053 1086
    #     puts response.body
1054 1087
    #
1055
    #     # using block
1088
    #     # Using a block
1056 1089
    #     http.request_get('/index.html') {|response|
1057 1090
    #       p response['content-type']
1058 1091
    #       response.read_body do |str|   # read body now
......
1064 1097
      request(Get.new(path, initheader), &block)
1065 1098
    end
1066 1099

  
1067
    # Sends a HEAD request to the +path+ and gets a response,
1068
    # as an HTTPResponse object.
1100
    # Sends a HEAD request to the +path+ and returns the response
1101
    # as a Net::HTTPResponse object.
1069 1102
    #
1070 1103
    # Returns the response.
1071 1104
    #
......
1078 1111
      request(Head.new(path, initheader), &block)
1079 1112
    end
1080 1113

  
1081
    # Sends a POST request to the +path+ and gets a response,
1082
    # as an HTTPResponse object.
1114
    # Sends a POST request to the +path+.
1083 1115
    #
1084
    # When called with a block, yields an HTTPResponse object.
1085
    # The body of this response will not have been read yet;
1086
    # the caller can process it using HTTPResponse#read_body,
1087
    # if desired.
1116
    # Returns the response as a Net::HTTPResponse object.
1117
    # 
1118
    # When called with a block, the block is passed an HTTPResponse 
1119
    # object.  The body of that response will not have been read yet;
1120
    # the block can process it using HTTPResponse#read_body, if desired.
1088 1121
    #
1089 1122
    # Returns the response.
1090 1123
    #
......
1093 1126
    #     # example
1094 1127
    #     response = http.request_post('/cgi-bin/nice.rb', 'datadatadata...')
1095 1128
    #     p response.status
1096
    #     puts response.body          # body is already read
1129
    #     puts response.body          # body is already read in this case
1097 1130
    #
1098 1131
    #     # using block
1099 1132
    #     http.request_post('/cgi-bin/nice.rb', 'datadatadata...') {|response|
......
1119 1152

  
1120 1153

  
1121 1154
    # Sends an HTTP request to the HTTP server.
1122
    # This method also sends DATA string if DATA is given.
1155
    # Also sends a DATA string if +data+ is given.
1123 1156
    #
1124
    # Returns a HTTPResponse object.
1157
    # Returns a Net::HTTPResponse object.
1125 1158
    #
1126 1159
    # This method never raises Net::* exceptions.
1127 1160
    #
......
1133 1166
      request r, data
1134 1167
    end
1135 1168

  
1136
    # Sends an HTTPRequest object REQUEST to the HTTP server.
1137
    # This method also sends DATA string if REQUEST is a post/put request.
1138
    # Giving DATA for get/head request causes ArgumentError.
1169
    # Sends an HTTPRequest object +req+ to the HTTP server.
1139 1170
    #
1140
    # When called with a block, yields an HTTPResponse object.
1141
    # The body of this response will not have been read yet;
1142
    # the caller can process it using HTTPResponse#read_body,
1171
    # If +req+ is a Net::HTTP::Post or Net::HTTP::Put request containing 
1172
    # data, the data is also sent. Providing data for a Net::HTTP::Head or
1173
    # Net::HTTP::Get request results in an ArgumentError.
1174
    # 
1175
    # Returns an HTTPResponse object.
1176
    # 
1177
    # When called with a block, passes an HTTPResponse object to the block.
1178
    # The body of the response will not have been read yet;
1179
    # the block can process it using HTTPResponse#read_body,
1143 1180
    # if desired.
1144
    #
1145
    # Returns a HTTPResponse object.
1146
    #
1181
    # 
1147 1182
    # This method never raises Net::* exceptions.
1148 1183
    #
1149 1184
    def request(req, body = nil, &block)  # :yield: +response+
......
1284 1319
  HTTPSession = HTTP
1285 1320

  
1286 1321

  
1322
  # The HTTPHeader module defines methods for reading and writing
1323
  # HTTP headers.
1287 1324
  #
1288
  # Header module.
1325
  # It is used as a mixin by other classes, to provide hash-like
1326
  # access to HTTP header values. Unlike raw hash access, HTTPHeader
1327
  # provides access via case-insensitive keys. It also provides 
1328
  # methods for accessing commonly-used HTTP header values in more
1329
  # convenient formats.
1289 1330
  #
1290
  # Provides access to @header in the mixed-into class as a hash-like
1291
  # object, except with case-insensitive keys.  Also provides
1292
  # methods for accessing commonly-used header values in a more
1293
  # convenient format.
1294
  #
1295 1331
  module HTTPHeader
1296 1332

  
1297 1333
    def initialize_http_header(initheader)
......
1326 1362
    end
1327 1363

  
1328 1364
    # [Ruby 1.8.3]
1329
    # Adds header field instead of replace.
1365
    # Adds a value to a named header field, instead of replacing its value.
1330 1366
    # Second argument +val+ must be a String.
1331 1367
    # See also #[]=, #[] and #get_fields.
1332 1368
    #
......
1366 1402

  
1367 1403
    # Returns the header field corresponding to the case-insensitive key.
1368 1404
    # Returns the default value +args+, or the result of the block, or
1369
    # raises an IndexErrror if there's no header field named +key+
1405
    # raises an IndexError if there's no header field named +key+
1370 1406
    # See Hash#fetch
1371 1407
    def fetch(key, *args, &block)   #:yield: +key+
1372 1408
      a = @header.fetch(key.downcase, *args, &block)
1373 1409
      a.kind_of?(Array) ? a.join(', ') : a
1374 1410
    end
1375 1411

  
1376
    # Iterates for each header names and values.
1412
    # Iterates through the header names and values, passing in the name
1413
    # and value to the code block supplied.
1414
    #
1415
    # Example:
1416
    #
1417
    #     response.header.each_header {|key,value| puts "#{key} = #{value}" }
1418
    #
1377 1419
    def each_header   #:yield: +key+, +value+
1378 1420
      block_given? or return enum_for(__method__)
1379 1421
      @header.each do |k,va|
......
1383 1425

  
1384 1426
    alias each each_header
1385 1427

  
1386
    # Iterates for each header names.
1428
    # Iterates through the header names in the header, passing
1429
    # each header name to the code block.
1387 1430
    def each_name(&block)   #:yield: +key+
1388 1431
      block_given? or return enum_for(__method__)
1389 1432
      @header.each_key(&block)
......
1391 1434

  
1392 1435
    alias each_key each_name
1393 1436

  
1394
    # Iterates for each capitalized header names.
1437
    # Iterates through the header names in the header, passing 
1438
    # capitalized header names to the code block.
1439
    #
1440
    # Note that header names are capitalized systematically; 
1441
    # capitalization may not match that used by the remote HTTP 
1442
    # server in its response.
1395 1443
    def each_capitalized_name  #:yield: +key+
1396 1444
      block_given? or return enum_for(__method__)
1397 1445
      @header.each_key do |k|
......
1399 1447
      end
1400 1448
    end
1401 1449

  
1402
    # Iterates for each header values.
1450
    # Iterates through header values, passing each value to the
1451
    # code block.
1403 1452
    def each_value   #:yield: +value+
1404 1453
      block_given? or return enum_for(__method__)
1405 1454
      @header.each_value do |va|
......
1407 1456
      end
1408 1457
    end
1409 1458

  
1410
    # Removes a header field.
1459
    # Removes a header field, specified by case-insensitive key.
1411 1460
    def delete(key)
1412 1461
      @header.delete(key.downcase)
1413 1462
    end
......
1417 1466
      @header.key?(key.downcase)
1418 1467
    end
1419 1468

  
1420
    # Returns a Hash consist of header names and values.
1469
    # Returns a Hash consisting of header names and values.
1470
    # e.g.
1471
    # {"cache-control" => "private",
1472
    #  "content-type" => "text/html",
1473
    #  "date" => "Wed, 22 Jun 2005 22:11:50 GMT"}
1421 1474
    def to_hash
1422 1475
      @header.dup
1423 1476
    end
1424 1477

  
1425 1478
    # As for #each_header, except the keys are provided in capitalized form.
1479
    #
1480
    # Note that header names are capitalized systematically; 
1481
    # capitalization may not match that used by the remote HTTP 
1482
    # server in its response.
1426 1483
    def each_capitalized
1427 1484
      block_given? or return enum_for(__method__)
1428 1485
      @header.each do |k,v|
......
1437 1494
    end
1438 1495
    private :capitalize
1439 1496

  
1440
    # Returns an Array of Range objects which represents Range: header field,
1441
    # or +nil+ if there is no such header.
1497
    # Returns an Array of Range objects which represent the Range: 
1498
    # HTTP header field, or +nil+ if there is no such header.
1442 1499
    def range
1443 1500
      return nil unless @header['range']
1444 1501
      self['Range'].split(/,/).map {|spec|
......
1455 1512
      }
1456 1513
    end
1457 1514

  
1458
    # Set Range: header from Range (arg r) or beginning index and
1459
    # length from it (arg idx&len).
1515
    # Sets the HTTP Range: header.
1516
    # Accepts either a Range object as a single argument,
1517
    # or a beginning index and a length from that index.
1518
    # Example:
1460 1519
    #
1461 1520
    #   req.range = (0..1023)
1462 1521
    #   req.set_range 0, 1023
......
1492 1551

  
1493 1552
    alias range= set_range
1494 1553

  
1495
    # Returns an Integer object which represents the Content-Length: header field
1496
    # or +nil+ if that field is not provided.
1554
    # Returns an Integer object which represents the HTTP Content-Length:
1555
    # header field, or +nil+ if that field was not provided.
1497 1556
    def content_length
1498 1557
      return nil unless key?('Content-Length')
1499 1558
      len = self['Content-Length'].slice(/\d+/) or
......
1519 1578
      (/(?:\A|[^\-\w])chunked(?![\-\w])/i =~ field) ? true : false
1520 1579
    end
1521 1580

  
1522
    # Returns a Range object which represents Content-Range: header field.
1523
    # This indicates, for a partial entity body, where this fragment
1581
    # Returns a Range object which represents the value of the Content-Range:
1582
    # header field.
1583
    # For a partial entity body, this indicates where this fragment
1524 1584
    # fits inside the full entity body, as range of byte offsets.
1525 1585
    def content_range
1526 1586
      return nil unless @header['content-range']
......
1562 1622
      sub.strip
1563 1623
    end
1564 1624

  
1565
    # Returns content type parameters as a Hash as like
1566
    # {"charset" => "iso-2022-jp"}.
1625
    # Any parameters specified for the content type, returned as a Hash.
1626
    # For example, a header of Content-Type: text/html; charset=EUC-JP
1627
    # would result in type_params returning {'charset' => 'EUC-JP'}
1567 1628
    def type_params
1568 1629
      result = {}
1569 1630
      list = self['Content-Type'].to_s.split(';')
......
1575 1636
      result
1576 1637
    end
1577 1638

  
1578
    # Set Content-Type: header field by +type+ and +params+.
1579
    # +type+ must be a String, +params+ must be a Hash.
1639
    # Sets the content type in an HTTP header.
1640
    # The +type+ should be a full HTTP content type, e.g. "text/html".
1641
    # The +params+ are an optional Hash of parameters to add after the
1642
    # content type, e.g. {'charset' => 'iso-8859-1'}
1580 1643
    def set_content_type(type, params = {})
1581 1644
      @header['content-type'] = [type + params.map{|k,v|"; #{k}=#{v}"}.join('')]
1582 1645
    end
......
1587 1650
    # +params+ should be a Hash containing HTML form data.
1588 1651
    # Optional argument +sep+ means data record separator.
1589 1652
    #
1590
    # This method also set Content-Type: header field to
1591
    # application/x-www-form-urlencoded.
1653
    # Values are URL encoded as necessary and the content-type is set to 
1654
    # application/x-www-form-urlencoded
1592 1655
    #
1593 1656
    # Example:
1594 1657
    #    http.form_data = {"q" => "ruby", "lang" => "en"}
......
1648 1711
  end
1649 1712

  
1650 1713

  
1714
  # HTTPGenericRequest is the parent of the HTTPRequest class.
1715
  # Do not use this directly; use a subclass of HTTPRequest.
1651 1716
  #
1652
  # Parent of HTTPRequest class.  Do not use this directly; use
1653
  # a subclass of HTTPRequest.
1717
  # Mixes in the HTTPHeader module to provide easier access to HTTP headers.
1654 1718
  #
1655
  # Mixes in the HTTPHeader module.
1656
  #
1657 1719
  class HTTPGenericRequest
1658 1720

  
1659 1721
    include HTTPHeader
......
1775 1837

  
1776 1838

  
1777 1839
  #
1778
  # HTTP request class. This class wraps request header and entity path.
1779
  # You *must* use its subclass, Net::HTTP::Get, Post, Head.
1840
  # HTTP request class. 
1841
  # This class wraps together the request header and the request path.
1842
  # You cannot use this class directly. Instead, you should use one of its
1843
  # subclasses: Net::HTTP::Get, Net::HTTP::Post, Net::HTTP::Head.
1780 1844
  #
1781 1845
  class HTTPRequest < HTTPGenericRequest
1782 1846

  
......
1795 1859
    # HTTP/1.1 methods --- RFC2616
1796 1860
    #
1797 1861

  
1862
    # See Net::HTTPGenericRequest for attributes and methods.
1863
    # See Net::HTTP for usage examples.
1798 1864
    class Get < HTTPRequest
1799 1865
      METHOD = 'GET'
1800 1866
      REQUEST_HAS_BODY  = false
1801 1867
      RESPONSE_HAS_BODY = true
1802 1868
    end
1803 1869

  
1870
    # See Net::HTTPGenericRequest for attributes and methods.
1871
    # See Net::HTTP for usage examples.
1804 1872
    class Head < HTTPRequest
1805 1873
      METHOD = 'HEAD'
1806 1874
      REQUEST_HAS_BODY = false
1807 1875
      RESPONSE_HAS_BODY = false
1808 1876
    end
1809 1877

  
1878
    # See Net::HTTPGenericRequest for attributes and methods.
1879
    # See Net::HTTP for usage examples.
1810 1880
    class Post < HTTPRequest
1811 1881
      METHOD = 'POST'
1812 1882
      REQUEST_HAS_BODY = true
1813 1883
      RESPONSE_HAS_BODY = true
1814 1884
    end
1815 1885

  
1886
    # See Net::HTTPGenericRequest for attributes and methods.
1887
    # See Net::HTTP for usage examples.
1816 1888
    class Put < HTTPRequest
1817 1889
      METHOD = 'PUT'
1818 1890
      REQUEST_HAS_BODY = true
1819 1891
      RESPONSE_HAS_BODY = true
1820 1892
    end
1821 1893

  
1894
    # See Net::HTTPGenericRequest for attributes and methods.
1895
    # See Net::HTTP for usage examples.
1822 1896
    class Delete < HTTPRequest
1823 1897
      METHOD = 'DELETE'
1824 1898
      REQUEST_HAS_BODY = false
1825 1899
      RESPONSE_HAS_BODY = true
1826 1900
    end
1827 1901

  
1902
    # See Net::HTTPGenericRequest for attributes and methods.
1828 1903
    class Options < HTTPRequest
1829 1904
      METHOD = 'OPTIONS'
1830 1905
      REQUEST_HAS_BODY = false
1831 1906
      RESPONSE_HAS_BODY = false
1832 1907
    end
1833 1908

  
1909
    # See Net::HTTPGenericRequest for attributes and methods.
1834 1910
    class Trace < HTTPRequest
1835 1911
      METHOD = 'TRACE'
1836 1912
      REQUEST_HAS_BODY = false
......
1840 1916
    #
1841 1917
    # PATCH method --- RFC5789
1842 1918
    #
1843

  
1919
 
1920
    # See Net::HTTPGenericRequest for attributes and methods.
1844 1921
    class Patch < HTTPRequest
1845 1922
      METHOD = 'PATCH'
1846 1923
      REQUEST_HAS_BODY = true
......
1851 1928
    # WebDAV methods --- RFC2518
1852 1929
    #
1853 1930

  
1931
    # See Net::HTTPGenericRequest for attributes and methods.
1854 1932
    class Propfind < HTTPRequest
1855 1933
      METHOD = 'PROPFIND'
1856 1934
      REQUEST_HAS_BODY = true
1857 1935
      RESPONSE_HAS_BODY = true
1858 1936
    end
1859 1937

  
1938
    # See Net::HTTPGenericRequest for attributes and methods.
1860 1939
    class Proppatch < HTTPRequest
1861 1940
      METHOD = 'PROPPATCH'
1862 1941
      REQUEST_HAS_BODY = true
1863 1942
      RESPONSE_HAS_BODY = true
1864 1943
    end
1865 1944

  
1945
    # See Net::HTTPGenericRequest for attributes and methods.
1866 1946
    class Mkcol < HTTPRequest
1867 1947
      METHOD = 'MKCOL'
1868 1948
      REQUEST_HAS_BODY = true
1869 1949
      RESPONSE_HAS_BODY = true
1870 1950
    end
1871 1951

  
1952
    # See Net::HTTPGenericRequest for attributes and methods.
1872 1953
    class Copy < HTTPRequest
1873 1954
      METHOD = 'COPY'
1874 1955
      REQUEST_HAS_BODY = false
1875 1956
      RESPONSE_HAS_BODY = true
1876 1957
    end
1877 1958

  
1959
    # See Net::HTTPGenericRequest for attributes and methods.
1878 1960
    class Move < HTTPRequest
1879 1961
      METHOD = 'MOVE'
1880 1962
      REQUEST_HAS_BODY = false
1881 1963
      RESPONSE_HAS_BODY = true
1882 1964
    end
1883 1965

  
1966
    # See Net::HTTPGenericRequest for attributes and methods.
1884 1967
    class Lock < HTTPRequest
1885 1968
      METHOD = 'LOCK'
1886 1969
      REQUEST_HAS_BODY = true
1887 1970
      RESPONSE_HAS_BODY = true
1888 1971
    end
1889 1972

  
1973
    # See Net::HTTPGenericRequest for attributes and methods.
1890 1974
    class Unlock < HTTPRequest
1891 1975
      METHOD = 'UNLOCK'
1892 1976
      REQUEST_HAS_BODY = true
......
1900 1984
  ###
1901 1985

  
1902 1986
  # HTTP exception class.
1903
  # You must use its subclasses.
1987
  # You cannot use HTTPExceptions directly; instead, you must use 
1988
  # its subclasses.
1904 1989
  module HTTPExceptions
1905 1990
    def initialize(msg, res)   #:nodoc:
1906 1991
      super msg
......
1924 2009
  end
1925 2010

  
1926 2011

  
1927
  # HTTP response class. This class wraps response header and entity.
1928
  # Mixes in the HTTPHeader module, which provides access to response
1929
  # header values both via hash-like methods and individual readers.
2012
  # HTTP response class. 
2013
  #
2014
  # This class wraps together the response header and the response body (the
2015
  # entity requested).
2016
  #
2017
  # It mixes in the HTTPHeader module, which provides access to response
2018
  # header values both via hash-like methods and via individual readers.
2019
  #
1930 2020
  # Note that each possible HTTP response code defines its own
1931 2021
  # HTTPResponse subclass.  These are listed below.
2022
  #
1932 2023
  # All classes are
1933 2024
  # defined under the Net module. Indentation indicates inheritance.
1934 2025
  #
......
2272 2363
    # The HTTP version supported by the server.
2273 2364
    attr_reader :http_version
2274 2365

  
2275
    # HTTP result code string. For example, '302'.  You can also
2276
    # determine the response type by which response subclass the
2277
    # response object is an instance of.
2366
    # The HTTP result code string. For example, '302'.  You can also
2367
    # determine the response type by examining which response subclass 
2368
    # the response object is an instance of.
2278 2369
    attr_reader :code
2279 2370

  
2280
    # HTTP result message. For example, 'Not Found'.
2371
    # The HTTP result message sent by the server. For example, 'Not Found'.
2281 2372
    attr_reader :message
2282 2373
    alias msg message   # :nodoc: obsolete
2283 2374

  
......
2315 2406
      self.class::EXCEPTION_TYPE
2316 2407
    end
2317 2408

  
2318
    # Raises HTTP error if the response is not 2xx.
2409
    # Raises an HTTP error if the response is not 2xx (success).
2319 2410
    def value
2320 2411
      error! unless self.kind_of?(HTTPSuccess)
2321 2412
    end
......
2354 2445
      end
2355 2446
    end
2356 2447

  
2357
    # Gets entity body.  If the block given, yields it to +block+.
2358
    # The body is provided in fragments, as it is read in from the socket.
2448
    # Gets the entity body returned by the remote HTTP server.
2359 2449
    #
2360
    # Calling this method a second or subsequent time will return the
2361
    # already read string.
2450
    # If a block is given, the body is passed to the block, and 
2451
    # the body is provided in fragments, as it is read in from the socket.
2362 2452
    #
2453
    # Calling this method a second or subsequent time for the same
2454
    # HTTPResponse object will return the value already read.
2455
    #
2363 2456
    #   http.request_get('/index.html') {|res|
2364 2457
    #     puts res.read_body
2365 2458
    #   }
......
2394 2487
      @body
2395 2488
    end
2396 2489

  
2397
    # Returns the entity body.
2490
    # Returns the full entity body.
2398 2491
    #
2399 2492
    # Calling this method a second or subsequent time will return the
2400
    # already read string.
2493
    # string already read.
2401 2494
    #
2402 2495
    #   http.request_get('/index.html') {|res|
2403 2496
    #     puts res.body