-
Notifications
You must be signed in to change notification settings - Fork 66
/
http.rb
2580 lines (2407 loc) · 86.3 KB
/
http.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# frozen_string_literal: true
#
# = net/http.rb
#
# Copyright (c) 1999-2007 Yukihiro Matsumoto
# Copyright (c) 1999-2007 Minero Aoki
# Copyright (c) 2001 GOTOU Yuuzou
#
# Written and maintained by Minero Aoki <[email protected]>.
# HTTPS support added by GOTOU Yuuzou <[email protected]>.
#
# This file is derived from "http-access.rb".
#
# Documented by Minero Aoki; converted to RDoc by William Webber.
#
# This program is free software. You can re-distribute and/or
# modify this program under the same terms of ruby itself ---
# Ruby Distribution License or GNU General Public License.
#
# See Net::HTTP for an overview and examples.
#
require 'net/protocol'
require 'uri'
require 'resolv'
autoload :OpenSSL, 'openssl'
module Net #:nodoc:
# :stopdoc:
class HTTPBadResponse < StandardError; end
class HTTPHeaderSyntaxError < StandardError; end
# :startdoc:
# \Class \Net::HTTP provides a rich library that implements the client
# in a client-server model that uses the \HTTP request-response protocol.
# For information about \HTTP, see:
#
# - {Hypertext Transfer Protocol}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol].
# - {Technical overview}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Technical_overview].
#
# == About the Examples
#
# :include: doc/net-http/examples.rdoc
#
# == Strategies
#
# - If you will make only a few GET requests,
# consider using {OpenURI}[https://docs.ruby-lang.org/en/master/OpenURI.html].
# - If you will make only a few requests of all kinds,
# consider using the various singleton convenience methods in this class.
# Each of the following methods automatically starts and finishes
# a {session}[rdoc-ref:Net::HTTP@Sessions] that sends a single request:
#
# # Return string response body.
# Net::HTTP.get(hostname, path)
# Net::HTTP.get(uri)
#
# # Write string response body to $stdout.
# Net::HTTP.get_print(hostname, path)
# Net::HTTP.get_print(uri)
#
# # Return response as Net::HTTPResponse object.
# Net::HTTP.get_response(hostname, path)
# Net::HTTP.get_response(uri)
# data = '{"title": "foo", "body": "bar", "userId": 1}'
# Net::HTTP.post(uri, data)
# params = {title: 'foo', body: 'bar', userId: 1}
# Net::HTTP.post_form(uri, params)
# data = '{"title": "foo", "body": "bar", "userId": 1}'
# Net::HTTP.put(uri, data)
#
# - If performance is important, consider using sessions, which lower request overhead.
# This {session}[rdoc-ref:Net::HTTP@Sessions] has multiple requests for
# {HTTP methods}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods]
# and {WebDAV methods}[https://en.wikipedia.org/wiki/WebDAV#Implementation]:
#
# Net::HTTP.start(hostname) do |http|
# # Session started automatically before block execution.
# http.get(path)
# http.head(path)
# body = 'Some text'
# http.post(path, body) # Can also have a block.
# http.put(path, body)
# http.delete(path)
# http.options(path)
# http.trace(path)
# http.patch(path, body) # Can also have a block.
# http.copy(path)
# http.lock(path, body)
# http.mkcol(path, body)
# http.move(path)
# http.propfind(path, body)
# http.proppatch(path, body)
# http.unlock(path, body)
# # Session finished automatically at block exit.
# end
#
# The methods cited above are convenience methods that, via their few arguments,
# allow minimal control over the requests.
# For greater control, consider using {request objects}[rdoc-ref:Net::HTTPRequest].
#
# == URIs
#
# On the internet, a URI
# ({Universal Resource Identifier}[https://en.wikipedia.org/wiki/Uniform_Resource_Identifier])
# is a string that identifies a particular resource.
# It consists of some or all of: scheme, hostname, path, query, and fragment;
# see {URI syntax}[https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax].
#
# A Ruby {URI::Generic}[https://docs.ruby-lang.org/en/master/URI/Generic.html] object
# represents an internet URI.
# It provides, among others, methods
# +scheme+, +hostname+, +path+, +query+, and +fragment+.
#
# === Schemes
#
# An internet \URI has
# a {scheme}[https://en.wikipedia.org/wiki/List_of_URI_schemes].
#
# The two schemes supported in \Net::HTTP are <tt>'https'</tt> and <tt>'http'</tt>:
#
# uri.scheme # => "https"
# URI('http://example.com').scheme # => "http"
#
# === Hostnames
#
# A hostname identifies a server (host) to which requests may be sent:
#
# hostname = uri.hostname # => "jsonplaceholder.typicode.com"
# Net::HTTP.start(hostname) do |http|
# # Some HTTP stuff.
# end
#
# === Paths
#
# A host-specific path identifies a resource on the host:
#
# _uri = uri.dup
# _uri.path = '/todos/1'
# hostname = _uri.hostname
# path = _uri.path
# Net::HTTP.get(hostname, path)
#
# === Queries
#
# A host-specific query adds name/value pairs to the URI:
#
# _uri = uri.dup
# params = {userId: 1, completed: false}
# _uri.query = URI.encode_www_form(params)
# _uri # => #<URI::HTTPS https://jsonplaceholder.typicode.com?userId=1&completed=false>
# Net::HTTP.get(_uri)
#
# === Fragments
#
# A {URI fragment}[https://en.wikipedia.org/wiki/URI_fragment] has no effect
# in \Net::HTTP;
# the same data is returned, regardless of whether a fragment is included.
#
# == Request Headers
#
# Request headers may be used to pass additional information to the host,
# similar to arguments passed in a method call;
# each header is a name/value pair.
#
# Each of the \Net::HTTP methods that sends a request to the host
# has optional argument +headers+,
# where the headers are expressed as a hash of field-name/value pairs:
#
# headers = {Accept: 'application/json', Connection: 'Keep-Alive'}
# Net::HTTP.get(uri, headers)
#
# See lists of both standard request fields and common request fields at
# {Request Fields}[https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#Request_fields].
# A host may also accept other custom fields.
#
# == \HTTP Sessions
#
# A _session_ is a connection between a server (host) and a client that:
#
# - Is begun by instance method Net::HTTP#start.
# - May contain any number of requests.
# - Is ended by instance method Net::HTTP#finish.
#
# See example sessions at {Strategies}[rdoc-ref:Net::HTTP@Strategies].
#
# === Session Using \Net::HTTP.start
#
# If you have many requests to make to a single host (and port),
# consider using singleton method Net::HTTP.start with a block;
# the method handles the session automatically by:
#
# - Calling #start before block execution.
# - Executing the block.
# - Calling #finish after block execution.
#
# In the block, you can use these instance methods,
# each of which that sends a single request:
#
# - {HTTP methods}[https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods]:
#
# - #get, #request_get: GET.
# - #head, #request_head: HEAD.
# - #post, #request_post: POST.
# - #delete: DELETE.
# - #options: OPTIONS.
# - #trace: TRACE.
# - #patch: PATCH.
#
# - {WebDAV methods}[https://en.wikipedia.org/wiki/WebDAV#Implementation]:
#
# - #copy: COPY.
# - #lock: LOCK.
# - #mkcol: MKCOL.
# - #move: MOVE.
# - #propfind: PROPFIND.
# - #proppatch: PROPPATCH.
# - #unlock: UNLOCK.
#
# === Session Using \Net::HTTP.start and \Net::HTTP.finish
#
# You can manage a session manually using methods #start and #finish:
#
# http = Net::HTTP.new(hostname)
# http.start
# http.get('/todos/1')
# http.get('/todos/2')
# http.delete('/posts/1')
# http.finish # Needed to free resources.
#
# === Single-Request Session
#
# Certain convenience methods automatically handle a session by:
#
# - Creating an \HTTP object
# - Starting a session.
# - Sending a single request.
# - Finishing the session.
# - Destroying the object.
#
# Such methods that send GET requests:
#
# - ::get: Returns the string response body.
# - ::get_print: Writes the string response body to $stdout.
# - ::get_response: Returns a Net::HTTPResponse object.
#
# Such methods that send POST requests:
#
# - ::post: Posts data to the host.
# - ::post_form: Posts form data to the host.
#
# == \HTTP Requests and Responses
#
# Many of the methods above are convenience methods,
# each of which sends a request and returns a string
# without directly using \Net::HTTPRequest and \Net::HTTPResponse objects.
#
# You can, however, directly create a request object, send the request,
# and retrieve the response object; see:
#
# - Net::HTTPRequest.
# - Net::HTTPResponse.
#
# == Following Redirection
#
# Each returned response is an instance of a subclass of Net::HTTPResponse.
# See the {response class hierarchy}[rdoc-ref:Net::HTTPResponse@Response+Subclasses].
#
# In particular, class Net::HTTPRedirection is the parent
# of all redirection classes.
# This allows you to craft a case statement to handle redirections properly:
#
# def fetch(uri, limit = 10)
# # You should choose a better exception.
# raise ArgumentError, 'Too many HTTP redirects' if limit == 0
#
# res = Net::HTTP.get_response(URI(uri))
# case res
# when Net::HTTPSuccess # Any success class.
# res
# when Net::HTTPRedirection # Any redirection class.
# location = res['Location']
# warn "Redirected to #{location}"
# fetch(location, limit - 1)
# else # Any other class.
# res.value
# end
# end
#
# fetch(uri)
#
# == Basic Authentication
#
# Basic authentication is performed according to
# {RFC2617}[http://www.ietf.org/rfc/rfc2617.txt]:
#
# req = Net::HTTP::Get.new(uri)
# req.basic_auth('user', 'pass')
# res = Net::HTTP.start(hostname) do |http|
# http.request(req)
# end
#
# == Streaming Response Bodies
#
# By default \Net::HTTP reads an entire response into memory. If you are
# handling large files or wish to implement a progress bar you can instead
# stream the body directly to an IO.
#
# Net::HTTP.start(hostname) do |http|
# req = Net::HTTP::Get.new(uri)
# http.request(req) do |res|
# open('t.tmp', 'w') do |f|
# res.read_body do |chunk|
# f.write chunk
# end
# end
# end
# end
#
# == HTTPS
#
# HTTPS is enabled for an \HTTP connection by Net::HTTP#use_ssl=:
#
# Net::HTTP.start(hostname, :use_ssl => true) do |http|
# req = Net::HTTP::Get.new(uri)
# res = http.request(req)
# end
#
# Or if you simply want to make a GET request, you may pass in a URI
# object that has an \HTTPS URL. \Net::HTTP automatically turns on TLS
# verification if the URI object has a 'https' URI scheme:
#
# uri # => #<URI::HTTPS https://jsonplaceholder.typicode.com/>
# Net::HTTP.get(uri)
#
# == Proxy Server
#
# An \HTTP object can have
# a {proxy server}[https://en.wikipedia.org/wiki/Proxy_server].
#
# You can create an \HTTP object with a proxy server
# using method Net::HTTP.new or method Net::HTTP.start.
#
# The proxy may be defined either by argument +p_addr+
# or by environment variable <tt>'http_proxy'</tt>.
#
# === Proxy Using Argument +p_addr+ as a \String
#
# When argument +p_addr+ is a string hostname,
# the returned +http+ has the given host as its proxy:
#
# http = Net::HTTP.new(hostname, nil, 'proxy.example')
# http.proxy? # => true
# http.proxy_from_env? # => false
# http.proxy_address # => "proxy.example"
# # These use default values.
# http.proxy_port # => 80
# http.proxy_user # => nil
# http.proxy_pass # => nil
#
# The port, username, and password for the proxy may also be given:
#
# http = Net::HTTP.new(hostname, nil, 'proxy.example', 8000, 'pname', 'ppass')
# # => #<Net::HTTP jsonplaceholder.typicode.com:80 open=false>
# http.proxy? # => true
# http.proxy_from_env? # => false
# http.proxy_address # => "proxy.example"
# http.proxy_port # => 8000
# http.proxy_user # => "pname"
# http.proxy_pass # => "ppass"
#
# === Proxy Using '<tt>ENV['http_proxy']</tt>'
#
# When environment variable <tt>'http_proxy'</tt>
# is set to a \URI string,
# the returned +http+ will have the server at that URI as its proxy;
# note that the \URI string must have a protocol
# such as <tt>'http'</tt> or <tt>'https'</tt>:
#
# ENV['http_proxy'] = 'http://example.com'
# http = Net::HTTP.new(hostname)
# http.proxy? # => true
# http.proxy_from_env? # => true
# http.proxy_address # => "example.com"
# # These use default values.
# http.proxy_port # => 80
# http.proxy_user # => nil
# http.proxy_pass # => nil
#
# The \URI string may include proxy username, password, and port number:
#
# ENV['http_proxy'] = 'http://pname:[email protected]:8000'
# http = Net::HTTP.new(hostname)
# http.proxy? # => true
# http.proxy_from_env? # => true
# http.proxy_address # => "example.com"
# http.proxy_port # => 8000
# http.proxy_user # => "pname"
# http.proxy_pass # => "ppass"
#
# === Filtering Proxies
#
# With method Net::HTTP.new (but not Net::HTTP.start),
# you can use argument +p_no_proxy+ to filter proxies:
#
# - Reject a certain address:
#
# http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example')
# http.proxy_address # => nil
#
# - Reject certain domains or subdomains:
#
# http = Net::HTTP.new('example.com', nil, 'my.proxy.example', 8000, 'pname', 'ppass', 'proxy.example')
# http.proxy_address # => nil
#
# - Reject certain addresses and port combinations:
#
# http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example:1234')
# http.proxy_address # => "proxy.example"
#
# http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'proxy.example:8000')
# http.proxy_address # => nil
#
# - Reject a list of the types above delimited using a comma:
#
# http = Net::HTTP.new('example.com', nil, 'proxy.example', 8000, 'pname', 'ppass', 'my.proxy,proxy.example:8000')
# http.proxy_address # => nil
#
# http = Net::HTTP.new('example.com', nil, 'my.proxy', 8000, 'pname', 'ppass', 'my.proxy,proxy.example:8000')
# http.proxy_address # => nil
#
# == Compression and Decompression
#
# \Net::HTTP does not compress the body of a request before sending.
#
# By default, \Net::HTTP adds header <tt>'Accept-Encoding'</tt>
# to a new {request object}[rdoc-ref:Net::HTTPRequest]:
#
# Net::HTTP::Get.new(uri)['Accept-Encoding']
# # => "gzip;q=1.0,deflate;q=0.6,identity;q=0.3"
#
# This requests the server to zip-encode the response body if there is one;
# the server is not required to do so.
#
# \Net::HTTP does not automatically decompress a response body
# if the response has header <tt>'Content-Range'</tt>.
#
# Otherwise decompression (or not) depends on the value of header
# {Content-Encoding}[https://en.wikipedia.org/wiki/List_of_HTTP_header_fields#content-encoding-response-header]:
#
# - <tt>'deflate'</tt>, <tt>'gzip'</tt>, or <tt>'x-gzip'</tt>:
# decompresses the body and deletes the header.
# - <tt>'none'</tt> or <tt>'identity'</tt>:
# does not decompress the body, but deletes the header.
# - Any other value:
# leaves the body and header unchanged.
#
# == What's Here
#
# First, what's elsewhere. Class Net::HTTP:
#
# - Inherits from {class Object}[https://docs.ruby-lang.org/en/master/Object.html#class-Object-label-What-27s+Here].
#
# This is a categorized summary of methods and attributes.
#
# === \Net::HTTP Objects
#
# - {::new}[rdoc-ref:Net::HTTP.new]:
# Creates a new instance.
# - {#inspect}[rdoc-ref:Net::HTTP#inspect]:
# Returns a string representation of +self+.
#
# === Sessions
#
# - {::start}[rdoc-ref:Net::HTTP.start]:
# Begins a new session in a new \Net::HTTP object.
# - {#started?}[rdoc-ref:Net::HTTP#started?]
# (aliased as {#active?}[rdoc-ref:Net::HTTP#active?]):
# Returns whether in a session.
# - {#finish}[rdoc-ref:Net::HTTP#finish]:
# Ends an active session.
# - {#start}[rdoc-ref:Net::HTTP#start]:
# Begins a new session in an existing \Net::HTTP object (+self+).
#
# === Connections
#
# - {:continue_timeout}[rdoc-ref:Net::HTTP#continue_timeout]:
# Returns the continue timeout.
# - {#continue_timeout=}[rdoc-ref:Net::HTTP#continue_timeout=]:
# Sets the continue timeout seconds.
# - {:keep_alive_timeout}[rdoc-ref:Net::HTTP#keep_alive_timeout]:
# Returns the keep-alive timeout.
# - {:keep_alive_timeout=}[rdoc-ref:Net::HTTP#keep_alive_timeout=]:
# Sets the keep-alive timeout.
# - {:max_retries}[rdoc-ref:Net::HTTP#max_retries]:
# Returns the maximum retries.
# - {#max_retries=}[rdoc-ref:Net::HTTP#max_retries=]:
# Sets the maximum retries.
# - {:open_timeout}[rdoc-ref:Net::HTTP#open_timeout]:
# Returns the open timeout.
# - {:open_timeout=}[rdoc-ref:Net::HTTP#open_timeout=]:
# Sets the open timeout.
# - {:read_timeout}[rdoc-ref:Net::HTTP#read_timeout]:
# Returns the open timeout.
# - {:read_timeout=}[rdoc-ref:Net::HTTP#read_timeout=]:
# Sets the read timeout.
# - {:ssl_timeout}[rdoc-ref:Net::HTTP#ssl_timeout]:
# Returns the ssl timeout.
# - {:ssl_timeout=}[rdoc-ref:Net::HTTP#ssl_timeout=]:
# Sets the ssl timeout.
# - {:write_timeout}[rdoc-ref:Net::HTTP#write_timeout]:
# Returns the write timeout.
# - {write_timeout=}[rdoc-ref:Net::HTTP#write_timeout=]:
# Sets the write timeout.
#
# === Requests
#
# - {::get}[rdoc-ref:Net::HTTP.get]:
# Sends a GET request and returns the string response body.
# - {::get_print}[rdoc-ref:Net::HTTP.get_print]:
# Sends a GET request and write the string response body to $stdout.
# - {::get_response}[rdoc-ref:Net::HTTP.get_response]:
# Sends a GET request and returns a response object.
# - {::post_form}[rdoc-ref:Net::HTTP.post_form]:
# Sends a POST request with form data and returns a response object.
# - {::post}[rdoc-ref:Net::HTTP.post]:
# Sends a POST request with data and returns a response object.
# - {::put}[rdoc-ref:Net::HTTP.put]:
# Sends a PUT request with data and returns a response object.
# - {#copy}[rdoc-ref:Net::HTTP#copy]:
# Sends a COPY request and returns a response object.
# - {#delete}[rdoc-ref:Net::HTTP#delete]:
# Sends a DELETE request and returns a response object.
# - {#get}[rdoc-ref:Net::HTTP#get]:
# Sends a GET request and returns a response object.
# - {#head}[rdoc-ref:Net::HTTP#head]:
# Sends a HEAD request and returns a response object.
# - {#lock}[rdoc-ref:Net::HTTP#lock]:
# Sends a LOCK request and returns a response object.
# - {#mkcol}[rdoc-ref:Net::HTTP#mkcol]:
# Sends a MKCOL request and returns a response object.
# - {#move}[rdoc-ref:Net::HTTP#move]:
# Sends a MOVE request and returns a response object.
# - {#options}[rdoc-ref:Net::HTTP#options]:
# Sends a OPTIONS request and returns a response object.
# - {#patch}[rdoc-ref:Net::HTTP#patch]:
# Sends a PATCH request and returns a response object.
# - {#post}[rdoc-ref:Net::HTTP#post]:
# Sends a POST request and returns a response object.
# - {#propfind}[rdoc-ref:Net::HTTP#propfind]:
# Sends a PROPFIND request and returns a response object.
# - {#proppatch}[rdoc-ref:Net::HTTP#proppatch]:
# Sends a PROPPATCH request and returns a response object.
# - {#put}[rdoc-ref:Net::HTTP#put]:
# Sends a PUT request and returns a response object.
# - {#request}[rdoc-ref:Net::HTTP#request]:
# Sends a request and returns a response object.
# - {#request_get}[rdoc-ref:Net::HTTP#request_get]
# (aliased as {#get2}[rdoc-ref:Net::HTTP#get2]):
# Sends a GET request and forms a response object;
# if a block given, calls the block with the object,
# otherwise returns the object.
# - {#request_head}[rdoc-ref:Net::HTTP#request_head]
# (aliased as {#head2}[rdoc-ref:Net::HTTP#head2]):
# Sends a HEAD request and forms a response object;
# if a block given, calls the block with the object,
# otherwise returns the object.
# - {#request_post}[rdoc-ref:Net::HTTP#request_post]
# (aliased as {#post2}[rdoc-ref:Net::HTTP#post2]):
# Sends a POST request and forms a response object;
# if a block given, calls the block with the object,
# otherwise returns the object.
# - {#send_request}[rdoc-ref:Net::HTTP#send_request]:
# Sends a request and returns a response object.
# - {#trace}[rdoc-ref:Net::HTTP#trace]:
# Sends a TRACE request and returns a response object.
# - {#unlock}[rdoc-ref:Net::HTTP#unlock]:
# Sends an UNLOCK request and returns a response object.
#
# === Responses
#
# - {:close_on_empty_response}[rdoc-ref:Net::HTTP#close_on_empty_response]:
# Returns whether to close connection on empty response.
# - {:close_on_empty_response=}[rdoc-ref:Net::HTTP#close_on_empty_response=]:
# Sets whether to close connection on empty response.
# - {:ignore_eof}[rdoc-ref:Net::HTTP#ignore_eof]:
# Returns whether to ignore end-of-file when reading a response body
# with <tt>Content-Length</tt> headers.
# - {:ignore_eof=}[rdoc-ref:Net::HTTP#ignore_eof=]:
# Sets whether to ignore end-of-file when reading a response body
# with <tt>Content-Length</tt> headers.
# - {:response_body_encoding}[rdoc-ref:Net::HTTP#response_body_encoding]:
# Returns the encoding to use for the response body.
# - {#response_body_encoding=}[rdoc-ref:Net::HTTP#response_body_encoding=]:
# Sets the response body encoding.
#
# === Proxies
#
# - {:proxy_address}[rdoc-ref:Net::HTTP#proxy_address]:
# Returns the proxy address.
# - {:proxy_address=}[rdoc-ref:Net::HTTP#proxy_address=]:
# Sets the proxy address.
# - {::proxy_class?}[rdoc-ref:Net::HTTP.proxy_class?]:
# Returns whether +self+ is a proxy class.
# - {#proxy?}[rdoc-ref:Net::HTTP#proxy?]:
# Returns whether +self+ has a proxy.
# - {#proxy_address}[rdoc-ref:Net::HTTP#proxy_address]
# (aliased as {#proxyaddr}[rdoc-ref:Net::HTTP#proxyaddr]):
# Returns the proxy address.
# - {#proxy_from_env?}[rdoc-ref:Net::HTTP#proxy_from_env?]:
# Returns whether the proxy is taken from an environment variable.
# - {:proxy_from_env=}[rdoc-ref:Net::HTTP#proxy_from_env=]:
# Sets whether the proxy is to be taken from an environment variable.
# - {:proxy_pass}[rdoc-ref:Net::HTTP#proxy_pass]:
# Returns the proxy password.
# - {:proxy_pass=}[rdoc-ref:Net::HTTP#proxy_pass=]:
# Sets the proxy password.
# - {:proxy_port}[rdoc-ref:Net::HTTP#proxy_port]:
# Returns the proxy port.
# - {:proxy_port=}[rdoc-ref:Net::HTTP#proxy_port=]:
# Sets the proxy port.
# - {#proxy_user}[rdoc-ref:Net::HTTP#proxy_user]:
# Returns the proxy user name.
# - {:proxy_user=}[rdoc-ref:Net::HTTP#proxy_user=]:
# Sets the proxy user.
#
# === Security
#
# - {:ca_file}[rdoc-ref:Net::HTTP#ca_file]:
# Returns the path to a CA certification file.
# - {:ca_file=}[rdoc-ref:Net::HTTP#ca_file=]:
# Sets the path to a CA certification file.
# - {:ca_path}[rdoc-ref:Net::HTTP#ca_path]:
# Returns the path of to CA directory containing certification files.
# - {:ca_path=}[rdoc-ref:Net::HTTP#ca_path=]:
# Sets the path of to CA directory containing certification files.
# - {:cert}[rdoc-ref:Net::HTTP#cert]:
# Returns the OpenSSL::X509::Certificate object to be used for client certification.
# - {:cert=}[rdoc-ref:Net::HTTP#cert=]:
# Sets the OpenSSL::X509::Certificate object to be used for client certification.
# - {:cert_store}[rdoc-ref:Net::HTTP#cert_store]:
# Returns the X509::Store to be used for verifying peer certificate.
# - {:cert_store=}[rdoc-ref:Net::HTTP#cert_store=]:
# Sets the X509::Store to be used for verifying peer certificate.
# - {:ciphers}[rdoc-ref:Net::HTTP#ciphers]:
# Returns the available SSL ciphers.
# - {:ciphers=}[rdoc-ref:Net::HTTP#ciphers=]:
# Sets the available SSL ciphers.
# - {:extra_chain_cert}[rdoc-ref:Net::HTTP#extra_chain_cert]:
# Returns the extra X509 certificates to be added to the certificate chain.
# - {:extra_chain_cert=}[rdoc-ref:Net::HTTP#extra_chain_cert=]:
# Sets the extra X509 certificates to be added to the certificate chain.
# - {:key}[rdoc-ref:Net::HTTP#key]:
# Returns the OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
# - {:key=}[rdoc-ref:Net::HTTP#key=]:
# Sets the OpenSSL::PKey::RSA or OpenSSL::PKey::DSA object.
# - {:max_version}[rdoc-ref:Net::HTTP#max_version]:
# Returns the maximum SSL version.
# - {:max_version=}[rdoc-ref:Net::HTTP#max_version=]:
# Sets the maximum SSL version.
# - {:min_version}[rdoc-ref:Net::HTTP#min_version]:
# Returns the minimum SSL version.
# - {:min_version=}[rdoc-ref:Net::HTTP#min_version=]:
# Sets the minimum SSL version.
# - {#peer_cert}[rdoc-ref:Net::HTTP#peer_cert]:
# Returns the X509 certificate chain for the session's socket peer.
# - {:ssl_version}[rdoc-ref:Net::HTTP#ssl_version]:
# Returns the SSL version.
# - {:ssl_version=}[rdoc-ref:Net::HTTP#ssl_version=]:
# Sets the SSL version.
# - {#use_ssl=}[rdoc-ref:Net::HTTP#use_ssl=]:
# Sets whether a new session is to use Transport Layer Security.
# - {#use_ssl?}[rdoc-ref:Net::HTTP#use_ssl?]:
# Returns whether +self+ uses SSL.
# - {:verify_callback}[rdoc-ref:Net::HTTP#verify_callback]:
# Returns the callback for the server certification verification.
# - {:verify_callback=}[rdoc-ref:Net::HTTP#verify_callback=]:
# Sets the callback for the server certification verification.
# - {:verify_depth}[rdoc-ref:Net::HTTP#verify_depth]:
# Returns the maximum depth for the certificate chain verification.
# - {:verify_depth=}[rdoc-ref:Net::HTTP#verify_depth=]:
# Sets the maximum depth for the certificate chain verification.
# - {:verify_hostname}[rdoc-ref:Net::HTTP#verify_hostname]:
# Returns the flags for server the certification verification at the beginning of the SSL/TLS session.
# - {:verify_hostname=}[rdoc-ref:Net::HTTP#verify_hostname=]:
# Sets he flags for server the certification verification at the beginning of the SSL/TLS session.
# - {:verify_mode}[rdoc-ref:Net::HTTP#verify_mode]:
# Returns the flags for server the certification verification at the beginning of the SSL/TLS session.
# - {:verify_mode=}[rdoc-ref:Net::HTTP#verify_mode=]:
# Sets the flags for server the certification verification at the beginning of the SSL/TLS session.
#
# === Addresses and Ports
#
# - {:address}[rdoc-ref:Net::HTTP#address]:
# Returns the string host name or host IP.
# - {::default_port}[rdoc-ref:Net::HTTP.default_port]:
# Returns integer 80, the default port to use for HTTP requests.
# - {::http_default_port}[rdoc-ref:Net::HTTP.http_default_port]:
# Returns integer 80, the default port to use for HTTP requests.
# - {::https_default_port}[rdoc-ref:Net::HTTP.https_default_port]:
# Returns integer 443, the default port to use for HTTPS requests.
# - {#ipaddr}[rdoc-ref:Net::HTTP#ipaddr]:
# Returns the IP address for the connection.
# - {#ipaddr=}[rdoc-ref:Net::HTTP#ipaddr=]:
# Sets the IP address for the connection.
# - {:local_host}[rdoc-ref:Net::HTTP#local_host]:
# Returns the string local host used to establish the connection.
# - {:local_host=}[rdoc-ref:Net::HTTP#local_host=]:
# Sets the string local host used to establish the connection.
# - {:local_port}[rdoc-ref:Net::HTTP#local_port]:
# Returns the integer local port used to establish the connection.
# - {:local_port=}[rdoc-ref:Net::HTTP#local_port=]:
# Sets the integer local port used to establish the connection.
# - {:port}[rdoc-ref:Net::HTTP#port]:
# Returns the integer port number.
#
# === \HTTP Version
#
# - {::version_1_2?}[rdoc-ref:Net::HTTP.version_1_2?]
# (aliased as {::is_version_1_2?}[rdoc-ref:Net::HTTP.is_version_1_2?]
# and {::version_1_2}[rdoc-ref:Net::HTTP.version_1_2]):
# Returns true; retained for compatibility.
#
# === Debugging
#
# - {#set_debug_output}[rdoc-ref:Net::HTTP#set_debug_output]:
# Sets the output stream for debugging.
#
class HTTP < Protocol
# :stopdoc:
VERSION = "0.5.0"
HTTPVersion = '1.1'
begin
require 'zlib'
HAVE_ZLIB=true
rescue LoadError
HAVE_ZLIB=false
end
# :startdoc:
# Returns +true+; retained for compatibility.
def HTTP.version_1_2
true
end
# Returns +true+; retained for compatibility.
def HTTP.version_1_2?
true
end
# Returns +false+; retained for compatibility.
def HTTP.version_1_1? #:nodoc:
false
end
class << HTTP
alias is_version_1_1? version_1_1? #:nodoc:
alias is_version_1_2? version_1_2? #:nodoc:
end
# :call-seq:
# Net::HTTP.get_print(hostname, path, port = 80) -> nil
# Net::HTTP:get_print(uri, headers = {}, port = uri.port) -> nil
#
# Like Net::HTTP.get, but writes the returned body to $stdout;
# returns +nil+.
def HTTP.get_print(uri_or_host, path_or_headers = nil, port = nil)
get_response(uri_or_host, path_or_headers, port) {|res|
res.read_body do |chunk|
$stdout.print chunk
end
}
nil
end
# :call-seq:
# Net::HTTP.get(hostname, path, port = 80) -> body
# Net::HTTP:get(uri, headers = {}, port = uri.port) -> body
#
# Sends a GET request and returns the \HTTP response body as a string.
#
# With string arguments +hostname+ and +path+:
#
# hostname = 'jsonplaceholder.typicode.com'
# path = '/todos/1'
# puts Net::HTTP.get(hostname, path)
#
# Output:
#
# {
# "userId": 1,
# "id": 1,
# "title": "delectus aut autem",
# "completed": false
# }
#
# With URI object +uri+ and optional hash argument +headers+:
#
# uri = URI('https://jsonplaceholder.typicode.com/todos/1')
# headers = {'Content-type' => 'application/json; charset=UTF-8'}
# Net::HTTP.get(uri, headers)
#
# Related:
#
# - Net::HTTP::Get: request class for \HTTP method +GET+.
# - Net::HTTP#get: convenience method for \HTTP method +GET+.
#
def HTTP.get(uri_or_host, path_or_headers = nil, port = nil)
get_response(uri_or_host, path_or_headers, port).body
end
# :call-seq:
# Net::HTTP.get_response(hostname, path, port = 80) -> http_response
# Net::HTTP:get_response(uri, headers = {}, port = uri.port) -> http_response
#
# Like Net::HTTP.get, but returns a Net::HTTPResponse object
# instead of the body string.
def HTTP.get_response(uri_or_host, path_or_headers = nil, port = nil, &block)
if path_or_headers && !path_or_headers.is_a?(Hash)
host = uri_or_host
path = path_or_headers
new(host, port || HTTP.default_port).start {|http|
return http.request_get(path, &block)
}
else
uri = uri_or_host
headers = path_or_headers
start(uri.hostname, uri.port,
:use_ssl => uri.scheme == 'https') {|http|
return http.request_get(uri, headers, &block)
}
end
end
# Posts data to a host; returns a Net::HTTPResponse object.
#
# Argument +url+ must be a URL;
# argument +data+ must be a string:
#
# _uri = uri.dup
# _uri.path = '/posts'
# data = '{"title": "foo", "body": "bar", "userId": 1}'
# headers = {'content-type': 'application/json'}
# res = Net::HTTP.post(_uri, data, headers) # => #<Net::HTTPCreated 201 Created readbody=true>
# puts res.body
#
# Output:
#
# {
# "title": "foo",
# "body": "bar",
# "userId": 1,
# "id": 101
# }
#
# Related:
#
# - Net::HTTP::Post: request class for \HTTP method +POST+.
# - Net::HTTP#post: convenience method for \HTTP method +POST+.
#
def HTTP.post(url, data, header = nil)
start(url.hostname, url.port,
:use_ssl => url.scheme == 'https' ) {|http|
http.post(url, data, header)
}
end
# Posts data to a host; returns a Net::HTTPResponse object.
#
# Argument +url+ must be a URI;
# argument +data+ must be a hash:
#
# _uri = uri.dup
# _uri.path = '/posts'
# data = {title: 'foo', body: 'bar', userId: 1}
# res = Net::HTTP.post_form(_uri, data) # => #<Net::HTTPCreated 201 Created readbody=true>
# puts res.body
#
# Output:
#
# {
# "title": "foo",
# "body": "bar",
# "userId": "1",
# "id": 101
# }
#
def HTTP.post_form(url, params)
req = Post.new(url)
req.form_data = params
req.basic_auth url.user, url.password if url.user
start(url.hostname, url.port,
:use_ssl => url.scheme == 'https' ) {|http|
http.request(req)
}
end
# Sends a PUT request to the server; returns a Net::HTTPResponse object.
#
# Argument +url+ must be a URL;
# argument +data+ must be a string:
#
# _uri = uri.dup
# _uri.path = '/posts'
# data = '{"title": "foo", "body": "bar", "userId": 1}'
# headers = {'content-type': 'application/json'}
# res = Net::HTTP.put(_uri, data, headers) # => #<Net::HTTPCreated 201 Created readbody=true>
# puts res.body
#
# Output:
#
# {
# "title": "foo",
# "body": "bar",
# "userId": 1,
# "id": 101
# }
#
# Related:
#
# - Net::HTTP::Put: request class for \HTTP method +PUT+.
# - Net::HTTP#put: convenience method for \HTTP method +PUT+.
#
def HTTP.put(url, data, header = nil)
start(url.hostname, url.port,
:use_ssl => url.scheme == 'https' ) {|http|
http.put(url, data, header)
}
end
#
# \HTTP session management
#
# Returns integer +80+, the default port to use for \HTTP requests:
#
# Net::HTTP.default_port # => 80
#
def HTTP.default_port
http_default_port()
end
# Returns integer +80+, the default port to use for \HTTP requests:
#
# Net::HTTP.http_default_port # => 80
#
def HTTP.http_default_port
80
end
# Returns integer +443+, the default port to use for HTTPS requests:
#
# Net::HTTP.https_default_port # => 443
#
def HTTP.https_default_port
443
end
def HTTP.socket_type #:nodoc: obsolete
BufferedIO
end
# :call-seq:
# HTTP.start(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, opts) -> http
# HTTP.start(address, port = nil, p_addr = :ENV, p_port = nil, p_user = nil, p_pass = nil, opts) {|http| ... } -> object
#
# Creates a new \Net::HTTP object, +http+, via \Net::HTTP.new:
#
# - For arguments +address+ and +port+, see Net::HTTP.new.
# - For proxy-defining arguments +p_addr+ through +p_pass+,
# see {Proxy Server}[rdoc-ref:Net::HTTP@Proxy+Server].
# - For argument +opts+, see below.
#
# With no block given:
#
# - Calls <tt>http.start</tt> with no block (see #start),
# which opens a TCP connection and \HTTP session.
# - Returns +http+.
# - The caller should call #finish to close the session:
#
# http = Net::HTTP.start(hostname)
# http.started? # => true
# http.finish
# http.started? # => false
#
# With a block given:
#
# - Calls <tt>http.start</tt> with the block (see #start), which:
#
# - Opens a TCP connection and \HTTP session.
# - Calls the block,
# which may make any number of requests to the host.
# - Closes the \HTTP session and TCP connection on block exit.
# - Returns the block's value +object+.
#
# - Returns +object+.
#
# Example: