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('docs.mojolicious.org')->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')->result->dom->find('h2 > a')->map('text')->join("\n");
27
28         # IPv6 PUT request with Content-Type header and content
29         my $tx = $ua->put('[::1]:3000' => {'Content-Type' => 'text/plain'} => 'Hi!');
30
31         # Quick JSON API request with Basic authentication
32         my $url = Mojo::URL->new('https://example.com/test.json')->userinfo('sri:☃');
33         my $value = $ua->get($url)->result->json;
34
35         # JSON POST (application/json) with TLS certificate authentication
36         my $tx = $ua->cert('tls.crt')->key('tls.key')->post('https://example.com' => json => {top => 'secret'});
37
38         # Form POST (application/x-www-form-urlencoded)
39         my $tx = $ua->post('https://metacpan.org/search' => form => {q => 'mojo'});
40
41         # Search DuckDuckGo anonymously through Tor
42         $ua->proxy->http('socks://127.0.0.1:9050');
43         say $ua->get('api.3g2upl4pq6kufc4m.onion/?q=mojolicious&format=json')->result->json('/Abstract');
44
45         # GET request via UNIX domain socket "/tmp/myapp.sock" (percent encoded slash)
46         say $ua->get('http+unix://%2Ftmp%2Fmyapp.sock/test')->result->body;
47
48         # Follow redirects to download Mojolicious from GitHub
49         $ua->max_redirects(5)
50           ->get('https://www.github.com/mojolicious/mojo/tarball/main')
51           ->result->save_to('/home/sri/mojo.tar.gz');
52
53         # Non-blocking request
54         $ua->get('mojolicious.org' => sub ($ua, $tx) { say $tx->result->dom->at('title')->text });
55         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
56
57         # Concurrent non-blocking requests (synchronized with promises)
58         my $mojo_promise = $ua->get_p('mojolicious.org');
59         my $cpan_promise = $ua->get_p('cpan.org');
60         Mojo::Promise->all($mojo_promise, $cpan_promise)->then(sub ($mojo, $cpan) {
61           say $mojo->[0]->result->dom->at('title')->text;
62           say $cpan->[0]->result->dom->at('title')->text;
63         })->wait;
64
65         # WebSocket connection sending and receiving JSON via UNIX domain socket
66         $ua->websocket('ws+unix://%2Ftmp%2Fmyapp.sock/echo.json' => sub ($ua, $tx) {
67           say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
68           $tx->on(json => sub ($tx, $hash) {
69             say "WebSocket message via JSON: $hash->{msg}";
70             $tx->finish;
71           });
72           $tx->send({json => {msg => 'Hello World!'}});
73         });
74         Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
75

DESCRIPTION

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

EVENTS

97       Mojo::UserAgent inherits all events from Mojo::EventEmitter and can
98       emit the following new ones.
99
100   prepare
101         $ua->on(prepare => sub ($ua, $tx) {...});
102
103       Emitted whenever a new transaction is being prepared, before relative
104       URLs are rewritten and cookies added. This includes automatically
105       prepared proxy "CONNECT" requests and followed redirects.
106
107         $ua->on(prepare => sub ($ua, $tx) {
108           $tx->req->url(Mojo::URL->new('/mock-mojolicious')) if $tx->req->url->host eq 'mojolicious.org';
109         });
110
111   start
112         $ua->on(start => sub ($ua, $tx) {...});
113
114       Emitted whenever a new transaction is about to start. This includes
115       automatically prepared proxy "CONNECT" requests and followed redirects.
116
117         $ua->on(start => sub ($ua, $tx) {
118           $tx->req->headers->header('X-Bender' => 'Bite my shiny metal ass!');
119         });
120

ATTRIBUTES

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

METHODS

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

DEBUGGING

631       You can set the "MOJO_CLIENT_DEBUG" environment variable to get some
632       advanced diagnostics information printed to "STDERR".
633
634         MOJO_CLIENT_DEBUG=1
635

SEE ALSO

637       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
638
639
640
641perl v5.36.0                      2023-01-20                Mojo::UserAgent(3)
Impressum