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   transactor
299         my $t = $ua->transactor;
300         $ua   = $ua->transactor(Mojo::UserAgent::Transactor->new);
301
302       Transaction builder, defaults to a Mojo::UserAgent::Transactor object.
303
304         # Change name of user agent
305         $ua->transactor->name('MyUA 1.0');
306
307         # Disable compression
308         $ua->transactor->compressed(0);
309

METHODS

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

DEBUGGING

625       You can set the "MOJO_CLIENT_DEBUG" environment variable to get some
626       advanced diagnostics information printed to "STDERR".
627
628         MOJO_CLIENT_DEBUG=1
629

SEE ALSO

631       Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
632
633
634
635perl v5.36.0                      2022-07-22                Mojo::UserAgent(3)
Impressum