1HTTP::Tiny(3) User Contributed Perl Documentation HTTP::Tiny(3)
2
3
4
6 HTTP::Tiny - A small, simple, correct HTTP/1.1 client
7
9 version 0.082
10
12 use HTTP::Tiny;
13
14 my $response = HTTP::Tiny->new->get('http://example.com/');
15
16 die "Failed!\n" unless $response->{success};
17
18 print "$response->{status} $response->{reason}\n";
19
20 while (my ($k, $v) = each %{$response->{headers}}) {
21 for (ref $v eq 'ARRAY' ? @$v : $v) {
22 print "$k: $_\n";
23 }
24 }
25
26 print $response->{content} if length $response->{content};
27
29 This is a very simple HTTP/1.1 client, designed for doing simple
30 requests without the overhead of a large framework like LWP::UserAgent.
31
32 It is more correct and more complete than HTTP::Lite. It supports
33 proxies and redirection. It also correctly resumes after EINTR.
34
35 If IO::Socket::IP 0.25 or later is installed, HTTP::Tiny will use it
36 instead of IO::Socket::INET for transparent support for both IPv4 and
37 IPv6.
38
39 Cookie support requires HTTP::CookieJar or an equivalent class.
40
42 new
43 $http = HTTP::Tiny->new( %attributes );
44
45 This constructor returns a new HTTP::Tiny object. Valid attributes
46 include:
47
48 • "agent" — A user-agent string (defaults to 'HTTP-Tiny/$VERSION').
49 If "agent" — ends in a space character, the default user-agent
50 string is appended.
51
52 • "cookie_jar" — An instance of HTTP::CookieJar — or equivalent class
53 that supports the "add" and "cookie_header" methods
54
55 • "default_headers" — A hashref of default headers to apply to
56 requests
57
58 • "local_address" — The local IP address to bind to
59
60 • "keep_alive" — Whether to reuse the last connection (if for the
61 same scheme, host and port) (defaults to 1)
62
63 • "max_redirect" — Maximum number of redirects allowed (defaults to
64 5)
65
66 • "max_size" — Maximum response size in bytes (only when not using a
67 data callback). If defined, requests with responses larger than
68 this will return a 599 status code.
69
70 • "http_proxy" — URL of a proxy server to use for HTTP connections
71 (default is $ENV{http_proxy} — if set)
72
73 • "https_proxy" — URL of a proxy server to use for HTTPS connections
74 (default is $ENV{https_proxy} — if set)
75
76 • "proxy" — URL of a generic proxy server for both HTTP and HTTPS
77 connections (default is $ENV{all_proxy} — if set)
78
79 • "no_proxy" — List of domain suffixes that should not be proxied.
80 Must be a comma-separated string or an array reference. (default is
81 $ENV{no_proxy} —)
82
83 • "timeout" — Request timeout in seconds (default is 60) If a socket
84 open, read or write takes longer than the timeout, the request
85 response status code will be 599.
86
87 • "verify_SSL" — A boolean that indicates whether to validate the SSL
88 certificate of an "https" — connection (default is false)
89
90 • "SSL_options" — A hashref of "SSL_*" — options to pass through to
91 IO::Socket::SSL
92
93 An accessor/mutator method exists for each attribute.
94
95 Passing an explicit "undef" for "proxy", "http_proxy" or "https_proxy"
96 will prevent getting the corresponding proxies from the environment.
97
98 Errors during request execution will result in a pseudo-HTTP status
99 code of 599 and a reason of "Internal Exception". The content field in
100 the response will contain the text of the error.
101
102 The "keep_alive" parameter enables a persistent connection, but only to
103 a single destination scheme, host and port. If any connection-relevant
104 attributes are modified via accessor, or if the process ID or thread ID
105 change, the persistent connection will be dropped. If you want
106 persistent connections across multiple destinations, use multiple
107 HTTP::Tiny objects.
108
109 See "SSL SUPPORT" for more on the "verify_SSL" and "SSL_options"
110 attributes.
111
112 get|head|put|post|patch|delete
113 $response = $http->get($url);
114 $response = $http->get($url, \%options);
115 $response = $http->head($url);
116
117 These methods are shorthand for calling "request()" for the given
118 method. The URL must have unsafe characters escaped and international
119 domain names encoded. See "request()" for valid options and a
120 description of the response.
121
122 The "success" field of the response will be true if the status code is
123 2XX.
124
125 post_form
126 $response = $http->post_form($url, $form_data);
127 $response = $http->post_form($url, $form_data, \%options);
128
129 This method executes a "POST" request and sends the key/value pairs
130 from a form data hash or array reference to the given URL with a
131 "content-type" of "application/x-www-form-urlencoded". If data is
132 provided as an array reference, the order is preserved; if provided as
133 a hash reference, the terms are sorted on key and value for
134 consistency. See documentation for the "www_form_urlencode" method for
135 details on the encoding.
136
137 The URL must have unsafe characters escaped and international domain
138 names encoded. See "request()" for valid options and a description of
139 the response. Any "content-type" header or content in the options
140 hashref will be ignored.
141
142 The "success" field of the response will be true if the status code is
143 2XX.
144
145 mirror
146 $response = $http->mirror($url, $file, \%options)
147 if ( $response->{success} ) {
148 print "$file is up to date\n";
149 }
150
151 Executes a "GET" request for the URL and saves the response body to the
152 file name provided. The URL must have unsafe characters escaped and
153 international domain names encoded. If the file already exists, the
154 request will include an "If-Modified-Since" header with the
155 modification timestamp of the file. You may specify a different
156 "If-Modified-Since" header yourself in the "$options->{headers}" hash.
157
158 The "success" field of the response will be true if the status code is
159 2XX or if the status code is 304 (unmodified).
160
161 If the file was modified and the server response includes a properly
162 formatted "Last-Modified" header, the file modification time will be
163 updated accordingly.
164
165 request
166 $response = $http->request($method, $url);
167 $response = $http->request($method, $url, \%options);
168
169 Executes an HTTP request of the given method type ('GET', 'HEAD',
170 'POST', 'PUT', etc.) on the given URL. The URL must have unsafe
171 characters escaped and international domain names encoded.
172
173 NOTE: Method names are case-sensitive per the HTTP/1.1 specification.
174 Don't use "get" when you really want "GET". See LIMITATIONS for how
175 this applies to redirection.
176
177 If the URL includes a "user:password" stanza, they will be used for
178 Basic-style authorization headers. (Authorization headers will not be
179 included in a redirected request.) For example:
180
181 $http->request('GET', 'http://Aladdin:open sesame@example.com/');
182
183 If the "user:password" stanza contains reserved characters, they must
184 be percent-escaped:
185
186 $http->request('GET', 'http://john%40example.com:password@example.com/');
187
188 A hashref of options may be appended to modify the request.
189
190 Valid options are:
191
192 • "headers" — A hashref containing headers to include with the
193 request. If the value for a header is an array reference, the
194 header will be output multiple times with each value in the array.
195 These headers over-write any default headers.
196
197 • "content" — A scalar to include as the body of the request OR a
198 code reference that will be called iteratively to produce the body
199 of the request
200
201 • "trailer_callback" — A code reference that will be called if it
202 exists to provide a hashref of trailing headers (only used with
203 chunked transfer-encoding)
204
205 • "data_callback" — A code reference that will be called for each
206 chunks of the response body received.
207
208 • "peer" — Override host resolution and force all connections to go
209 only to a specific peer address, regardless of the URL of the
210 request. This will include any redirections! This options should
211 be used with extreme caution (e.g. debugging or very special
212 circumstances). It can be given as either a scalar or a code
213 reference that will receive the hostname and whose response will be
214 taken as the address.
215
216 The "Host" header is generated from the URL in accordance with RFC
217 2616. It is a fatal error to specify "Host" in the "headers" option.
218 Other headers may be ignored or overwritten if necessary for transport
219 compliance.
220
221 If the "content" option is a code reference, it will be called
222 iteratively to provide the content body of the request. It should
223 return the empty string or undef when the iterator is exhausted.
224
225 If the "content" option is the empty string, no "content-type" or
226 "content-length" headers will be generated.
227
228 If the "data_callback" option is provided, it will be called
229 iteratively until the entire response body is received. The first
230 argument will be a string containing a chunk of the response body, the
231 second argument will be the in-progress response hash reference, as
232 described below. (This allows customizing the action of the callback
233 based on the "status" or "headers" received prior to the content body.)
234
235 Content data in the request/response is handled as "raw bytes". Any
236 encoding/decoding (with associated headers) are the responsibility of
237 the caller.
238
239 The "request" method returns a hashref containing the response. The
240 hashref will have the following keys:
241
242 • "success" — Boolean indicating whether the operation returned a 2XX
243 status code
244
245 • "url" — URL that provided the response. This is the URL of the
246 request unless there were redirections, in which case it is the
247 last URL queried in a redirection chain
248
249 • "status" — The HTTP status code of the response
250
251 • "reason" — The response phrase returned by the server
252
253 • "content" — The body of the response. If the response does not
254 have any content or if a data callback is provided to consume the
255 response body, this will be the empty string
256
257 • "headers" — A hashref of header fields. All header field names
258 will be normalized to be lower case. If a header is repeated, the
259 value will be an arrayref; it will otherwise be a scalar string
260 containing the value
261
262 • "protocol" - If this field exists, it is the protocol of the
263 response such as HTTP/1.0 or HTTP/1.1
264
265 • "redirects" If this field exists, it is an arrayref of response
266 hash references from redirects in the same order that redirections
267 occurred. If it does not exist, then no redirections occurred.
268
269 On an error during the execution of the request, the "status" field
270 will contain 599, and the "content" field will contain the text of the
271 error.
272
273 www_form_urlencode
274 $params = $http->www_form_urlencode( $data );
275 $response = $http->get("http://example.com/query?$params");
276
277 This method converts the key/value pairs from a data hash or array
278 reference into a "x-www-form-urlencoded" string. The keys and values
279 from the data reference will be UTF-8 encoded and escaped per RFC 3986.
280 If a value is an array reference, the key will be repeated with each of
281 the values of the array reference. If data is provided as a hash
282 reference, the key/value pairs in the resulting string will be sorted
283 by key and value for consistent ordering.
284
285 can_ssl
286 $ok = HTTP::Tiny->can_ssl;
287 ($ok, $why) = HTTP::Tiny->can_ssl;
288 ($ok, $why) = $http->can_ssl;
289
290 Indicates if SSL support is available. When called as a class object,
291 it checks for the correct version of Net::SSLeay and IO::Socket::SSL.
292 When called as an object methods, if "SSL_verify" is true or if
293 "SSL_verify_mode" is set in "SSL_options", it checks that a CA file is
294 available.
295
296 In scalar context, returns a boolean indicating if SSL is available.
297 In list context, returns the boolean and a (possibly multi-line) string
298 of errors indicating why SSL isn't available.
299
300 connected
301 $host = $http->connected;
302 ($host, $port) = $http->connected;
303
304 Indicates if a connection to a peer is being kept alive, per the
305 "keep_alive" option.
306
307 In scalar context, returns the peer host and port, joined with a colon,
308 or "undef" (if no peer is connected). In list context, returns the
309 peer host and port or an empty list (if no peer is connected).
310
311 Note: This method cannot reliably be used to discover whether the
312 remote host has closed its end of the socket.
313
315 Direct "https" connections are supported only if IO::Socket::SSL 1.56
316 or greater and Net::SSLeay 1.49 or greater are installed. An error will
317 occur if new enough versions of these modules are not installed or if
318 the SSL encryption fails. You can also use "HTTP::Tiny::can_ssl()"
319 utility function that returns boolean to see if the required modules
320 are installed.
321
322 An "https" connection may be made via an "http" proxy that supports the
323 CONNECT command (i.e. RFC 2817). You may not proxy "https" via a proxy
324 that itself requires "https" to communicate.
325
326 SSL provides two distinct capabilities:
327
328 • Encrypted communication channel
329
330 • Verification of server identity
331
332 By default, HTTP::Tiny does not verify server identity.
333
334 Server identity verification is controversial and potentially tricky
335 because it depends on a (usually paid) third-party Certificate
336 Authority (CA) trust model to validate a certificate as legitimate.
337 This discriminates against servers with self-signed certificates or
338 certificates signed by free, community-driven CA's such as CAcert.org
339 <http://cacert.org>.
340
341 By default, HTTP::Tiny does not make any assumptions about your trust
342 model, threat level or risk tolerance. It just aims to give you an
343 encrypted channel when you need one.
344
345 Setting the "verify_SSL" attribute to a true value will make HTTP::Tiny
346 verify that an SSL connection has a valid SSL certificate corresponding
347 to the host name of the connection and that the SSL certificate has
348 been verified by a CA. Assuming you trust the CA, this will protect
349 against a man-in-the-middle attack <http://en.wikipedia.org/wiki/Man-
350 in-the-middle_attack>. If you are concerned about security, you should
351 enable this option.
352
353 Certificate verification requires a file containing trusted CA
354 certificates.
355
356 If the environment variable "SSL_CERT_FILE" is present, HTTP::Tiny will
357 try to find a CA certificate file in that location.
358
359 If the Mozilla::CA module is installed, HTTP::Tiny will use the CA file
360 included with it as a source of trusted CA's. (This means you trust
361 Mozilla, the author of Mozilla::CA, the CPAN mirror where you got
362 Mozilla::CA, the toolchain used to install it, and your operating
363 system security, right?)
364
365 If that module is not available, then HTTP::Tiny will search several
366 system-specific default locations for a CA certificate file:
367
368 • /etc/ssl/certs/ca-certificates.crt
369
370 • /etc/pki/tls/certs/ca-bundle.crt
371
372 • /etc/ssl/ca-bundle.pem
373
374 An error will be occur if "verify_SSL" is true and no CA certificate
375 file is available.
376
377 If you desire complete control over SSL connections, the "SSL_options"
378 attribute lets you provide a hash reference that will be passed through
379 to "IO::Socket::SSL::start_SSL()", overriding any options set by
380 HTTP::Tiny. For example, to provide your own trusted CA file:
381
382 SSL_options => {
383 SSL_ca_file => $file_path,
384 }
385
386 The "SSL_options" attribute could also be used for such things as
387 providing a client certificate for authentication to a server or
388 controlling the choice of cipher used for the SSL connection. See
389 IO::Socket::SSL documentation for details.
390
392 HTTP::Tiny can proxy both "http" and "https" requests. Only Basic
393 proxy authorization is supported and it must be provided as part of the
394 proxy URL: "http://user:pass@proxy.example.com/".
395
396 HTTP::Tiny supports the following proxy environment variables:
397
398 • http_proxy or HTTP_PROXY
399
400 • https_proxy or HTTPS_PROXY
401
402 • all_proxy or ALL_PROXY
403
404 If the "REQUEST_METHOD" environment variable is set, then this might be
405 a CGI process and "HTTP_PROXY" would be set from the "Proxy:" header,
406 which is a security risk. If "REQUEST_METHOD" is set, "HTTP_PROXY"
407 (the upper case variant only) is ignored, but "CGI_HTTP_PROXY" is
408 considered instead.
409
410 Tunnelling "https" over an "http" proxy using the CONNECT method is
411 supported. If your proxy uses "https" itself, you can not tunnel
412 "https" over it.
413
414 Be warned that proxying an "https" connection opens you to the risk of
415 a man-in-the-middle attack by the proxy server.
416
417 The "no_proxy" environment variable is supported in the format of a
418 comma-separated list of domain extensions proxy should not be used for.
419
420 Proxy arguments passed to "new" will override their corresponding
421 environment variables.
422
424 HTTP::Tiny is conditionally compliant with the HTTP/1.1 specifications
425 <http://www.w3.org/Protocols/>:
426
427 • "Message Syntax and Routing" [RFC7230]
428
429 • "Semantics and Content" [RFC7231]
430
431 • "Conditional Requests" [RFC7232]
432
433 • "Range Requests" [RFC7233]
434
435 • "Caching" [RFC7234]
436
437 • "Authentication" [RFC7235]
438
439 It attempts to meet all "MUST" requirements of the specification, but
440 does not implement all "SHOULD" requirements. (Note: it was developed
441 against the earlier RFC 2616 specification and may not yet meet the
442 revised RFC 7230-7235 spec.) Additionally, HTTP::Tiny supports the
443 "PATCH" method of RFC 5789.
444
445 Some particular limitations of note include:
446
447 • HTTP::Tiny focuses on correct transport. Users are responsible for
448 ensuring that user-defined headers and content are compliant with
449 the HTTP/1.1 specification.
450
451 • Users must ensure that URLs are properly escaped for unsafe
452 characters and that international domain names are properly encoded
453 to ASCII. See URI::Escape, URI::_punycode and Net::IDN::Encode.
454
455 • Redirection is very strict against the specification. Redirection
456 is only automatic for response codes 301, 302, 307 and 308 if the
457 request method is 'GET' or 'HEAD'. Response code 303 is always
458 converted into a 'GET' redirection, as mandated by the
459 specification. There is no automatic support for status 305 ("Use
460 proxy") redirections.
461
462 • There is no provision for delaying a request body using an "Expect"
463 header. Unexpected "1XX" responses are silently ignored as per the
464 specification.
465
466 • Only 'chunked' "Transfer-Encoding" is supported.
467
468 • There is no support for a Request-URI of '*' for the 'OPTIONS'
469 request.
470
471 • Headers mentioned in the RFCs and some other, well-known headers
472 are generated with their canonical case. Other headers are sent in
473 the case provided by the user. Except for control headers (which
474 are sent first), headers are sent in arbitrary order.
475
476 Despite the limitations listed above, HTTP::Tiny is considered feature-
477 complete. New feature requests should be directed to HTTP::Tiny::UA.
478
480 • HTTP::Tiny::UA - Higher level UA features for HTTP::Tiny
481
482 • HTTP::Thin - HTTP::Tiny wrapper with HTTP::Request/HTTP::Response
483 compatibility
484
485 • HTTP::Tiny::Mech - Wrap WWW::Mechanize instance in HTTP::Tiny
486 compatible interface
487
488 • IO::Socket::IP - Required for IPv6 support
489
490 • IO::Socket::SSL - Required for SSL support
491
492 • LWP::UserAgent - If HTTP::Tiny isn't enough for you, this is the
493 "standard" way to do things
494
495 • Mozilla::CA - Required if you want to validate SSL certificates
496
497 • Net::SSLeay - Required for SSL support
498
500 Bugs / Feature Requests
501 Please report any bugs or feature requests through the issue tracker at
502 <https://github.com/chansen/p5-http-tiny/issues>. You will be notified
503 automatically of any progress on your issue.
504
505 Source Code
506 This is open source software. The code repository is available for
507 public review and contribution under the terms of the license.
508
509 <https://github.com/chansen/p5-http-tiny>
510
511 git clone https://github.com/chansen/p5-http-tiny.git
512
514 • Christian Hansen <chansen@cpan.org>
515
516 • David Golden <dagolden@cpan.org>
517
519 • Alan Gardner <gardner@pythian.com>
520
521 • Alessandro Ghedini <al3xbio@gmail.com>
522
523 • A. Sinan Unur <nanis@cpan.org>
524
525 • Brad Gilbert <bgills@cpan.org>
526
527 • brian m. carlson <sandals@crustytoothpaste.net>
528
529 • Chris Nehren <apeiron@cpan.org>
530
531 • Chris Weyl <cweyl@alumni.drew.edu>
532
533 • Claes Jakobsson <claes@surfar.nu>
534
535 • Clinton Gormley <clint@traveljury.com>
536
537 • Craig A. Berry <craigberry@mac.com>
538
539 • Craig Berry <cberry@cpan.org>
540
541 • David Golden <xdg@xdg.me>
542
543 • David Mitchell <davem@iabyn.com>
544
545 • Dean Pearce <pearce@pythian.com>
546
547 • Edward Zborowski <ed@rubensteintech.com>
548
549 • Felipe Gasper <felipe@felipegasper.com>
550
551 • Graham Knop <haarg@haarg.org>
552
553 • Greg Kennedy <kennedy.greg@gmail.com>
554
555 • James E Keenan <jkeenan@cpan.org>
556
557 • James Raspass <jraspass@gmail.com>
558
559 • Jeremy Mates <jmates@cpan.org>
560
561 • Jess Robinson <castaway@desert-island.me.uk>
562
563 • Karen Etheridge <ether@cpan.org>
564
565 • Lukas Eklund <leklund@gmail.com>
566
567 • Martin J. Evans <mjegh@ntlworld.com>
568
569 • Martin-Louis Bright <mlbright@gmail.com>
570
571 • Matthew Horsfall <wolfsage@gmail.com>
572
573 • Michael R. Davis <mrdvt92@users.noreply.github.com>
574
575 • Mike Doherty <doherty@cpan.org>
576
577 • Nicolas Rochelemagne <rochelemagne@cpanel.net>
578
579 • Olaf Alders <olaf@wundersolutions.com>
580
581 • Olivier Mengué <dolmen@cpan.org>
582
583 • Petr Písař <ppisar@redhat.com>
584
585 • sanjay-cpu <snjkmr32@gmail.com>
586
587 • Serguei Trouchelle <stro@cpan.org>
588
589 • Shoichi Kaji <skaji@cpan.org>
590
591 • SkyMarshal <skymarshal1729@gmail.com>
592
593 • Sören Kornetzki <soeren.kornetzki@delti.com>
594
595 • Steve Grazzini <steve.grazzini@grantstreet.com>
596
597 • Syohei YOSHIDA <syohex@gmail.com>
598
599 • Tatsuhiko Miyagawa <miyagawa@bulknews.net>
600
601 • Tom Hukins <tom@eborcom.com>
602
603 • Tony Cook <tony@develop-help.com>
604
605 • Xavier Guimard <yadd@debian.org>
606
608 This software is copyright (c) 2022 by Christian Hansen.
609
610 This is free software; you can redistribute it and/or modify it under
611 the same terms as the Perl 5 programming language system itself.
612
613
614
615perl v5.36.0 2022-07-26 HTTP::Tiny(3)