1Mojo::UserAgent(3)    User Contributed Perl Documentation   Mojo::UserAgent(3)
2
3
4

NAME

6       Mojo::UserAgent - Non-blocking I/O HTTP and WebSocket user agent
7

SYNOPSIS

9         use Mojo::UserAgent;
10
11         # Fine grained response handling (dies on connection errors)
12         my $ua  = Mojo::UserAgent->new;
13         my $res = $ua->get('mojolicious.org/perldoc')->result;
14         if    ($res->is_success)  { say $res->body }
15         elsif ($res->is_error)    { say $res->message }
16         elsif ($res->code == 301) { say $res->headers->location }
17         else                      { say 'Whatever...' }
18
19         # Say hello to the Unicode snowman and include an Accept header
20         say $ua->get('www.☃.net?hello=there' => {Accept => '*/*'})->result->body;
21
22         # Extract data from HTML and XML resources with CSS selectors
23         say $ua->get('www.perl.org')->result->dom->at('title')->text;
24
25         # Scrape the latest headlines from a news site
26         say $ua->get('blogs.perl.org')
27           ->result->dom->find('h2 > a')->map('text')->join("\n");
28
29         # IPv6 PUT request with Content-Type header and content
30         my $tx = $ua->put('[::1]:3000' => {'Content-Type' => 'text/plain'} => 'Hi!');
31
32         # Quick JSON API request with Basic authentication
33         my $url = Mojo::URL->new('https://example.com/test.json')->userinfo('sri:☃');
34         my $value = $ua->get($url)->result->json;
35
36         # JSON POST (application/json) with TLS certificate authentication
37         my $tx = $ua->cert('tls.crt')->key('tls.key')
38           ->post('https://example.com' => json => {top => 'secret'});
39
40         # Form POST (application/x-www-form-urlencoded)
41         my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});
42
43         # Search DuckDuckGo anonymously through Tor
44         $ua->proxy->http('socks://127.0.0.1:9050');
45         say $ua->get('api.3g2upl4pq6kufc4m.onion/?q=mojolicious&format=json')
46           ->result->json('/Abstract');
47
48         # GET request via UNIX domain socket "/tmp/myapp.sock" (percent encoded slash)
49         say $ua->get('http+unix://%2Ftmp%2Fmyapp.sock/perldoc')->result->body;
50
51         # Follow redirects to download Mojolicious from GitHub
52         $ua->max_redirects(5)
53           ->get('https://www.github.com/mojolicious/mojo/tarball/master')
54           ->result->save_to('/home/sri/mojo.tar.gz');
55
56         # Non-blocking request
57         $ua->get('mojolicious.org' => sub {
58           my ($ua, $tx) = @_;
59           say $tx->result->dom->at('title')->text;
60         });
61         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
62
63         # Concurrent non-blocking requests (synchronized with promises)
64         my $mojo = $ua->get_p('mojolicious.org');
65         my $cpan = $ua->get_p('cpan.org');
66         Mojo::Promise->all($mojo, $cpan)->then(sub {
67           my ($mojo, $cpan) = @_;
68           say $mojo->[0]->result->dom->at('title')->text;
69           say $cpan->[0]->result->dom->at('title')->text;
70         })->wait;
71
72         # WebSocket connection sending and receiving JSON via UNIX domain socket
73         $ua->websocket('ws+unix://%2Ftmp%2Fmyapp.sock/echo.json' => sub {
74           my ($ua, $tx) = @_;
75           say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
76           $tx->on(json => sub {
77             my ($tx, $hash) = @_;
78             say "WebSocket message via JSON: $hash->{msg}";
79             $tx->finish;
80           });
81           $tx->send({json => {msg => 'Hello World!'}});
82         });
83         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
84

DESCRIPTION

86       Mojo::UserAgent is a full featured non-blocking I/O HTTP and WebSocket
87       user agent, with IPv6, TLS, SNI, IDNA, HTTP/SOCKS5 proxy, UNIX domain
88       socket, Comet (long polling), Promises/A+, keep-alive, connection
89       pooling, timeout, cookie, multipart, gzip compression and multiple
90       event loop support.
91
92       All connections will be reset automatically if a new process has been
93       forked, this allows multiple processes to share the same
94       Mojo::UserAgent object safely.
95
96       For better scalability (epoll, kqueue) and to provide non-blocking name
97       resolution, SOCKS5 as well as TLS support, the optional modules EV
98       (4.0+), Net::DNS::Native (0.15+), IO::Socket::Socks (0.64+) and
99       IO::Socket::SSL (2.009+) will be used automatically if possible.
100       Individual features can also be disabled with the "MOJO_NO_NNR",
101       "MOJO_NO_SOCKS" and "MOJO_NO_TLS" environment variables.
102
103       See "USER AGENT" in Mojolicious::Guides::Cookbook for more.
104

EVENTS

106       Mojo::UserAgent inherits all events from Mojo::EventEmitter and can
107       emit the following new ones.
108
109   prepare
110         $ua->on(prepare => sub {
111           my ($ua, $tx) = @_;
112           ...
113         });
114
115       Emitted whenever a new transaction is being prepared, before relative
116       URLs are rewritten and cookies added. This includes automatically
117       prepared proxy "CONNECT" requests and followed redirects.
118
119         $ua->on(prepare => sub {
120           my ($ua, $tx) = @_;
121           $tx->req->url(Mojo::URL->new('/mock-mojolicious'))
122             if $tx->req->url->host eq 'mojolicious.org';
123         });
124
125   start
126         $ua->on(start => sub {
127           my ($ua, $tx) = @_;
128           ...
129         });
130
131       Emitted whenever a new transaction is about to start. This includes
132       automatically prepared proxy "CONNECT" requests and followed redirects.
133
134         $ua->on(start => sub {
135           my ($ua, $tx) = @_;
136           $tx->req->headers->header('X-Bender' => 'Bite my shiny metal ass!');
137         });
138

ATTRIBUTES

140       Mojo::UserAgent implements the following attributes.
141
142   ca
143         my $ca = $ua->ca;
144         $ua    = $ua->ca('/etc/tls/ca.crt');
145
146       Path to TLS certificate authority file used to verify the peer
147       certificate, defaults to the value of the "MOJO_CA_FILE" environment
148       variable.
149
150         # Show certificate authorities for debugging
151         IO::Socket::SSL::set_defaults(
152           SSL_verify_callback => sub { say "Authority: $_[2]" and return $_[0] });
153
154   cert
155         my $cert = $ua->cert;
156         $ua      = $ua->cert('/etc/tls/client.crt');
157
158       Path to TLS certificate file, defaults to the value of the
159       "MOJO_CERT_FILE" environment variable.
160
161   connect_timeout
162         my $timeout = $ua->connect_timeout;
163         $ua         = $ua->connect_timeout(5);
164
165       Maximum amount of time in seconds establishing a connection may take
166       before getting canceled, defaults to the value of the
167       "MOJO_CONNECT_TIMEOUT" environment variable or 10.
168
169   cookie_jar
170         my $cookie_jar = $ua->cookie_jar;
171         $ua            = $ua->cookie_jar(Mojo::UserAgent::CookieJar->new);
172
173       Cookie jar to use for requests performed by this user agent, defaults
174       to a Mojo::UserAgent::CookieJar object.
175
176         # Ignore all cookies
177         $ua->cookie_jar->ignore(sub { 1 });
178
179         # Ignore cookies for public suffixes
180         my $ps = IO::Socket::SSL::PublicSuffix->default;
181         $ua->cookie_jar->ignore(sub {
182           my $cookie = shift;
183           return undef unless my $domain = $cookie->domain;
184           return ($ps->public_suffix($domain))[0] eq '';
185         });
186
187         # Add custom cookie to the jar
188         $ua->cookie_jar->add(
189           Mojo::Cookie::Response->new(
190             name   => 'foo',
191             value  => 'bar',
192             domain => 'mojolicious.org',
193             path   => '/perldoc'
194           )
195         );
196
197   inactivity_timeout
198         my $timeout = $ua->inactivity_timeout;
199         $ua         = $ua->inactivity_timeout(15);
200
201       Maximum amount of time in seconds a connection can be inactive before
202       getting closed, defaults to the value of the "MOJO_INACTIVITY_TIMEOUT"
203       environment variable or 20. Setting the value to 0 will allow
204       connections to be inactive indefinitely.
205
206   insecure
207         my $bool = $ua->insecure;
208         $ua      = $ua->insecure($bool);
209
210       Do not require a valid TLS certificate to access HTTPS/WSS sites,
211       defaults to the value of the "MOJO_INSECURE" environment variable.
212
213         # Disable TLS certificate verification for testing
214         say $ua->insecure(1)->get('https://127.0.0.1:3000')->result->code;
215
216   ioloop
217         my $loop = $ua->ioloop;
218         $ua      = $ua->ioloop(Mojo::IOLoop->new);
219
220       Event loop object to use for blocking I/O operations, defaults to a
221       Mojo::IOLoop object.
222
223   key
224         my $key = $ua->key;
225         $ua     = $ua->key('/etc/tls/client.crt');
226
227       Path to TLS key file, defaults to the value of the "MOJO_KEY_FILE"
228       environment variable.
229
230   local_address
231         my $address = $ua->local_address;
232         $ua         = $ua->local_address('127.0.0.1');
233
234       Local address to bind to.
235
236   max_connections
237         my $max = $ua->max_connections;
238         $ua     = $ua->max_connections(5);
239
240       Maximum number of keep-alive connections that the user agent will
241       retain before it starts closing the oldest ones, defaults to 5. Setting
242       the value to 0 will prevent any connections from being kept alive.
243
244   max_redirects
245         my $max = $ua->max_redirects;
246         $ua     = $ua->max_redirects(3);
247
248       Maximum number of redirects the user agent will follow before it fails,
249       defaults to the value of the "MOJO_MAX_REDIRECTS" environment variable
250       or 0.
251
252   max_response_size
253         my $max = $ua->max_response_size;
254         $ua     = $ua->max_response_size(16777216);
255
256       Maximum response size in bytes, defaults to the value of
257       "max_message_size" in Mojo::Message::Response. Setting the value to 0
258       will allow responses of indefinite size. Note that increasing this
259       value can also drastically increase memory usage, should you for
260       example attempt to parse an excessively large response body with the
261       methods "dom" in Mojo::Message or "json" in Mojo::Message.
262
263   proxy
264         my $proxy = $ua->proxy;
265         $ua       = $ua->proxy(Mojo::UserAgent::Proxy->new);
266
267       Proxy manager, defaults to a Mojo::UserAgent::Proxy object.
268
269         # Detect proxy servers from environment
270         $ua->proxy->detect;
271
272         # Manually configure HTTP proxy (using CONNECT for HTTPS/WebSockets)
273         $ua->proxy->http('http://127.0.0.1:8080')->https('http://127.0.0.1:8080');
274
275         # Manually configure Tor (SOCKS5)
276         $ua->proxy->http('socks://127.0.0.1:9050')->https('socks://127.0.0.1:9050');
277
278         # Manually configure UNIX domain socket (using CONNECT for HTTPS/WebSockets)
279         $ua->proxy->http('http+unix://%2Ftmp%2Fproxy.sock')
280           ->https('http+unix://%2Ftmp%2Fproxy.sock');
281
282   request_timeout
283         my $timeout = $ua->request_timeout;
284         $ua         = $ua->request_timeout(5);
285
286       Maximum amount of time in seconds establishing a connection, sending
287       the request and receiving a whole response may take before getting
288       canceled, defaults to the value of the "MOJO_REQUEST_TIMEOUT"
289       environment variable or 0. Setting the value to 0 will allow the user
290       agent to wait indefinitely.  The timeout will reset for every followed
291       redirect.
292
293         # Total limit of 5 seconds, of which 3 seconds may be spent connecting
294         $ua->max_redirects(0)->connect_timeout(3)->request_timeout(5);
295
296   server
297         my $server = $ua->server;
298         $ua        = $ua->server(Mojo::UserAgent::Server->new);
299
300       Application server relative URLs will be processed with, defaults to a
301       Mojo::UserAgent::Server object.
302
303         # Mock web service
304         $ua->server->app(Mojolicious->new);
305         $ua->server->app->routes->get('/time' => sub {
306           my $c = shift;
307           $c->render(json => {now => time});
308         });
309         my $time = $ua->get('/time')->result->json->{now};
310
311         # Change log level
312         $ua->server->app->log->level('fatal');
313
314         # Port currently used for processing relative URLs blocking
315         say $ua->server->url->port;
316
317         # Port currently used for processing relative URLs non-blocking
318         say $ua->server->nb_url->port;
319
320   transactor
321         my $t = $ua->transactor;
322         $ua   = $ua->transactor(Mojo::UserAgent::Transactor->new);
323
324       Transaction builder, defaults to a Mojo::UserAgent::Transactor object.
325
326         # Change name of user agent
327         $ua->transactor->name('MyUA 1.0');
328
329         # Disable compression
330         $ua->transactor->compressed(0);
331

METHODS

333       Mojo::UserAgent inherits all methods from Mojo::EventEmitter and
334       implements the following new ones.
335
336   build_tx
337         my $tx = $ua->build_tx(GET => 'example.com');
338         my $tx = $ua->build_tx(
339           PUT => 'http://example.com' => {Accept => '*/*'} => 'Content!');
340         my $tx = $ua->build_tx(
341           PUT => 'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
342         my $tx = $ua->build_tx(
343           PUT => 'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
344
345       Generate Mojo::Transaction::HTTP object with "tx" in
346       Mojo::UserAgent::Transactor.
347
348         # Request with custom cookie
349         my $tx = $ua->build_tx(GET => 'https://example.com/account');
350         $tx->req->cookies({name => 'user', value => 'sri'});
351         $tx = $ua->start($tx);
352
353         # Deactivate gzip compression
354         my $tx = $ua->build_tx(GET => 'example.com');
355         $tx->req->headers->remove('Accept-Encoding');
356         $tx = $ua->start($tx);
357
358         # Interrupt response by raising an error
359         my $tx = $ua->build_tx(GET => 'http://example.com');
360         $tx->res->on(progress => sub {
361           my $res = shift;
362           return unless my $server = $res->headers->server;
363           $res->error({message => 'Oh noes, it is IIS!'}) if $server =~ /IIS/;
364         });
365         $tx = $ua->start($tx);
366
367   build_websocket_tx
368         my $tx = $ua->build_websocket_tx('ws://example.com');
369         my $tx = $ua->build_websocket_tx(
370           'ws://example.com' => {DNT => 1} => ['v1.proto']);
371
372       Generate Mojo::Transaction::HTTP object with "websocket" in
373       Mojo::UserAgent::Transactor.
374
375         # Custom WebSocket handshake with cookie
376         my $tx = $ua->build_websocket_tx('wss://example.com/echo');
377         $tx->req->cookies({name => 'user', value => 'sri'});
378         $ua->start($tx => sub {
379           my ($ua, $tx) = @_;
380           say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
381           $tx->on(message => sub {
382             my ($tx, $msg) = @_;
383             say "WebSocket message: $msg";
384             $tx->finish;
385           });
386           $tx->send('Hi!');
387         });
388         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
389
390   delete
391         my $tx = $ua->delete('example.com');
392         my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => 'Content!');
393         my $tx = $ua->delete(
394           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
395         my $tx = $ua->delete(
396           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
397
398       Perform blocking "DELETE" request and return resulting
399       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
400       Mojo::UserAgent::Transactor (except for the "DELETE" method, which is
401       implied). You can also append a callback to perform requests non-
402       blocking.
403
404         $ua->delete('http://example.com' => json => {a => 'b'} => sub {
405           my ($ua, $tx) = @_;
406           say $tx->result->body;
407         });
408         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
409
410   delete_p
411         my $promise = $ua->delete_p('http://example.com');
412
413       Same as "delete", but performs all requests non-blocking and returns a
414       Mojo::Promise object instead of accepting a callback.
415
416         $ua->delete_p('http://example.com' => json => {a => 'b'})->then(sub {
417           my $tx = shift;
418           say $tx->result->body;
419         })->catch(sub {
420           my $err = shift;
421           warn "Connection error: $err";
422         })->wait;
423
424   get
425         my $tx = $ua->get('example.com');
426         my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => 'Content!');
427         my $tx = $ua->get(
428           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
429         my $tx = $ua->get(
430           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
431
432       Perform blocking "GET" request and return resulting
433       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
434       Mojo::UserAgent::Transactor (except for the "GET" method, which is
435       implied). You can also append a callback to perform requests non-
436       blocking.
437
438         $ua->get('http://example.com' => json => {a => 'b'} => sub {
439           my ($ua, $tx) = @_;
440           say $tx->result->body;
441         });
442         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
443
444   get_p
445         my $promise = $ua->get_p('http://example.com');
446
447       Same as "get", but performs all requests non-blocking and returns a
448       Mojo::Promise object instead of accepting a callback.
449
450         $ua->get_p('http://example.com' => json => {a => 'b'})->then(sub {
451           my $tx = shift;
452           say $tx->result->body;
453         })->catch(sub {
454           my $err = shift;
455           warn "Connection error: $err";
456         })->wait;
457
458   head
459         my $tx = $ua->head('example.com');
460         my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => 'Content!');
461         my $tx = $ua->head(
462           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
463         my $tx = $ua->head(
464           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
465
466       Perform blocking "HEAD" request and return resulting
467       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
468       Mojo::UserAgent::Transactor (except for the "HEAD" method, which is
469       implied). You can also append a callback to perform requests non-
470       blocking.
471
472         $ua->head('http://example.com' => json => {a => 'b'} => sub {
473           my ($ua, $tx) = @_;
474           say $tx->result->body;
475         });
476         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
477
478   head_p
479         my $promise = $ua->head_p('http://example.com');
480
481       Same as "head", but performs all requests non-blocking and returns a
482       Mojo::Promise object instead of accepting a callback.
483
484         $ua->head_p('http://example.com' => json => {a => 'b'})->then(sub {
485           my $tx = shift;
486           say $tx->result->body;
487         })->catch(sub {
488           my $err = shift;
489           warn "Connection error: $err";
490         })->wait;
491
492   options
493         my $tx = $ua->options('example.com');
494         my $tx = $ua->options(
495           'http://example.com' => {Accept => '*/*'} => 'Content!');
496         my $tx = $ua->options(
497           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
498         my $tx = $ua->options(
499           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
500
501       Perform blocking "OPTIONS" request and return resulting
502       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
503       Mojo::UserAgent::Transactor (except for the "OPTIONS" method, which is
504       implied). You can also append a callback to perform requests non-
505       blocking.
506
507         $ua->options('http://example.com' => json => {a => 'b'} => sub {
508           my ($ua, $tx) = @_;
509           say $tx->result->body;
510         });
511         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
512
513   options_p
514         my $promise = $ua->options_p('http://example.com');
515
516       Same as "options", but performs all requests non-blocking and returns a
517       Mojo::Promise object instead of accepting a callback.
518
519         $ua->options_p('http://example.com' => json => {a => 'b'})->then(sub {
520           my $tx = shift;
521           say $tx->result->body;
522         })->catch(sub {
523           my $err = shift;
524           warn "Connection error: $err";
525         })->wait;
526
527   patch
528         my $tx = $ua->patch('example.com');
529         my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => 'Content!');
530         my $tx = $ua->patch(
531           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
532         my $tx = $ua->patch(
533           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
534
535       Perform blocking "PATCH" request and return resulting
536       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
537       Mojo::UserAgent::Transactor (except for the "PATCH" method, which is
538       implied). You can also append a callback to perform requests non-
539       blocking.
540
541         $ua->patch('http://example.com' => json => {a => 'b'} => sub {
542           my ($ua, $tx) = @_;
543           say $tx->result->body;
544         });
545         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
546
547   patch_p
548         my $promise = $ua->patch_p('http://example.com');
549
550       Same as "patch", but performs all requests non-blocking and returns a
551       Mojo::Promise object instead of accepting a callback.
552
553         $ua->patch_p('http://example.com' => json => {a => 'b'})->then(sub {
554           my $tx = shift;
555           say $tx->result->body;
556         })->catch(sub {
557           my $err = shift;
558           warn "Connection error: $err";
559         })->wait;
560
561   post
562         my $tx = $ua->post('example.com');
563         my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => 'Content!');
564         my $tx = $ua->post(
565           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
566         my $tx = $ua->post(
567           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
568
569       Perform blocking "POST" request and return resulting
570       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
571       Mojo::UserAgent::Transactor (except for the "POST" method, which is
572       implied). You can also append a callback to perform requests non-
573       blocking.
574
575         $ua->post('http://example.com' => json => {a => 'b'} => sub {
576           my ($ua, $tx) = @_;
577           say $tx->result->body;
578         });
579         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
580
581   post_p
582         my $promise = $ua->post_p('http://example.com');
583
584       Same as "post", but performs all requests non-blocking and returns a
585       Mojo::Promise object instead of accepting a callback.
586
587         $ua->post_p('http://example.com' => json => {a => 'b'})->then(sub {
588           my $tx = shift;
589           say $tx->result->body;
590         })->catch(sub {
591           my $err = shift;
592           warn "Connection error: $err";
593         })->wait;
594
595   put
596         my $tx = $ua->put('example.com');
597         my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => 'Content!');
598         my $tx = $ua->put(
599           'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
600         my $tx = $ua->put(
601           'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
602
603       Perform blocking "PUT" request and return resulting
604       Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
605       Mojo::UserAgent::Transactor (except for the "PUT" method, which is
606       implied). You can also append a callback to perform requests non-
607       blocking.
608
609         $ua->put('http://example.com' => json => {a => 'b'} => sub {
610           my ($ua, $tx) = @_;
611           say $tx->result->body;
612         });
613         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
614
615   put_p
616         my $promise = $ua->put_p('http://example.com');
617
618       Same as "put", but performs all requests non-blocking and returns a
619       Mojo::Promise object instead of accepting a callback.
620
621         $ua->put_p('http://example.com' => json => {a => 'b'})->then(sub {
622           my $tx = shift;
623           say $tx->result->body;
624         })->catch(sub {
625           my $err = shift;
626           warn "Connection error: $err";
627         })->wait;
628
629   start
630         my $tx = $ua->start(Mojo::Transaction::HTTP->new);
631
632       Perform blocking request for a custom Mojo::Transaction::HTTP object,
633       which can be prepared manually or with "build_tx". You can also append
634       a callback to perform requests non-blocking.
635
636         my $tx = $ua->build_tx(GET => 'http://example.com');
637         $ua->start($tx => sub {
638           my ($ua, $tx) = @_;
639           say $tx->result->body;
640         });
641         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
642
643   start_p
644         my $promise = $ua->start_p(Mojo::Transaction::HTTP->new);
645
646       Same as "start", but performs all requests non-blocking and returns a
647       Mojo::Promise object instead of accepting a callback.
648
649         my $tx = $ua->build_tx(GET => 'http://example.com');
650         $ua->start_p($tx)->then(sub {
651           my $tx = shift;
652           say $tx->result->body;
653         })->catch(sub {
654           my $err = shift;
655           warn "Connection error: $err";
656         })->wait;
657
658   websocket
659         $ua->websocket('ws://example.com' => sub {...});
660         $ua->websocket(
661           'ws://example.com' => {DNT => 1} => ['v1.proto'] => sub {...});
662
663       Open a non-blocking WebSocket connection with transparent handshake,
664       takes the same arguments as "websocket" in Mojo::UserAgent::Transactor.
665       The callback will receive either a Mojo::Transaction::WebSocket or
666       Mojo::Transaction::HTTP object, depending on if the handshake was
667       successful.
668
669         $ua->websocket('wss://example.com/echo' => ['v1.proto'] => sub {
670           my ($ua, $tx) = @_;
671           say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
672           say 'Subprotocol negotiation failed!' and return unless $tx->protocol;
673           $tx->on(finish => sub {
674             my ($tx, $code, $reason) = @_;
675             say "WebSocket closed with status $code.";
676           });
677           $tx->on(message => sub {
678             my ($tx, $msg) = @_;
679             say "WebSocket message: $msg";
680             $tx->finish;
681           });
682           $tx->send('Hi!');
683         });
684         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
685
686       You can activate "permessage-deflate" compression by setting the
687       "Sec-WebSocket-Extensions" header, this can result in much better
688       performance, but also increases memory usage by up to 300KiB per
689       connection.
690
691         $ua->websocket('ws://example.com/foo' => {
692           'Sec-WebSocket-Extensions' => 'permessage-deflate'
693         } => sub {...});
694
695   websocket_p
696         my $promise = $ua->websocket_p('ws://example.com');
697
698       Same as "websocket", but returns a Mojo::Promise object instead of
699       accepting a callback.
700
701         $ua->websocket_p('wss://example.com/echo')->then(sub {
702           my $tx = shift;
703           my $promise = Mojo::Promise->new;
704           $tx->on(finish => sub { $promise->resolve });
705           $tx->on(message => sub {
706             my ($tx, $msg) = @_;
707             say "WebSocket message: $msg";
708             $tx->finish;
709           });
710           $tx->send('Hi!');
711           return $promise;
712         })->catch(sub {
713           my $err = shift;
714           warn "WebSocket error: $err";
715         })->wait;
716

DEBUGGING

718       You can set the "MOJO_CLIENT_DEBUG" environment variable to get some
719       advanced diagnostics information printed to "STDERR".
720
721         MOJO_CLIENT_DEBUG=1
722

SEE ALSO

724       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
725
726
727
728perl v5.30.1                      2020-01-30                Mojo::UserAgent(3)
Impressum