1Mojo::UserAgent(3) User Contributed Perl Documentation Mojo::UserAgent(3)
2
3
4
6 Mojo::UserAgent - Non-blocking I/O HTTP and WebSocket user agent
7
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')->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/perldoc')->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/master')
51 ->result->save_to('/home/sri/mojo.tar.gz');
52
53 # Non-blocking request
54 $ua->get('mojolicious.org' => sub {
55 my ($ua, $tx) = @_;
56 say $tx->result->dom->at('title')->text;
57 });
58 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
59
60 # Concurrent non-blocking requests (synchronized with promises)
61 my $mojo = $ua->get_p('mojolicious.org');
62 my $cpan = $ua->get_p('cpan.org');
63 Mojo::Promise->all($mojo, $cpan)->then(sub {
64 my ($mojo, $cpan) = @_;
65 say $mojo->[0]->result->dom->at('title')->text;
66 say $cpan->[0]->result->dom->at('title')->text;
67 })->wait;
68
69 # WebSocket connection sending and receiving JSON via UNIX domain socket
70 $ua->websocket('ws+unix://%2Ftmp%2Fmyapp.sock/echo.json' => sub {
71 my ($ua, $tx) = @_;
72 say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
73 $tx->on(json => sub {
74 my ($tx, $hash) = @_;
75 say "WebSocket message via JSON: $hash->{msg}";
76 $tx->finish;
77 });
78 $tx->send({json => {msg => 'Hello World!'}});
79 });
80 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
81
83 Mojo::UserAgent is a full featured non-blocking I/O HTTP and WebSocket
84 user agent, with IPv6, TLS, SNI, IDNA, HTTP/SOCKS5 proxy, UNIX domain
85 socket, Comet (long polling), Promises/A+, keep-alive, connection
86 pooling, timeout, cookie, multipart, gzip compression and multiple
87 event loop support.
88
89 All connections will be reset automatically if a new process has been
90 forked, this allows multiple processes to share the same
91 Mojo::UserAgent object safely.
92
93 For better scalability (epoll, kqueue) and to provide non-blocking name
94 resolution, SOCKS5 as well as TLS support, the optional modules EV
95 (4.32+), Net::DNS::Native (0.15+), IO::Socket::Socks (0.64+) and
96 IO::Socket::SSL (2.009+) will be used automatically if possible.
97 Individual features can also be disabled with the "MOJO_NO_NNR",
98 "MOJO_NO_SOCKS" and "MOJO_NO_TLS" environment variables.
99
100 See "USER AGENT" in Mojolicious::Guides::Cookbook for more.
101
103 Mojo::UserAgent inherits all events from Mojo::EventEmitter and can
104 emit the following new ones.
105
106 prepare
107 $ua->on(prepare => sub {
108 my ($ua, $tx) = @_;
109 ...
110 });
111
112 Emitted whenever a new transaction is being prepared, before relative
113 URLs are rewritten and cookies added. This includes automatically
114 prepared proxy "CONNECT" requests and followed redirects.
115
116 $ua->on(prepare => sub {
117 my ($ua, $tx) = @_;
118 $tx->req->url(Mojo::URL->new('/mock-mojolicious')) if $tx->req->url->host eq 'mojolicious.org';
119 });
120
121 start
122 $ua->on(start => sub {
123 my ($ua, $tx) = @_;
124 ...
125 });
126
127 Emitted whenever a new transaction is about to start. This includes
128 automatically prepared proxy "CONNECT" requests and followed redirects.
129
130 $ua->on(start => sub {
131 my ($ua, $tx) = @_;
132 $tx->req->headers->header('X-Bender' => 'Bite my shiny metal ass!');
133 });
134
136 Mojo::UserAgent implements the following attributes.
137
138 ca
139 my $ca = $ua->ca;
140 $ua = $ua->ca('/etc/tls/ca.crt');
141
142 Path to TLS certificate authority file used to verify the peer
143 certificate, defaults to the value of the "MOJO_CA_FILE" environment
144 variable.
145
146 # Show certificate authorities for debugging
147 IO::Socket::SSL::set_defaults(SSL_verify_callback => sub { say "Authority: $_[2]" and return $_[0] });
148
149 cert
150 my $cert = $ua->cert;
151 $ua = $ua->cert('/etc/tls/client.crt');
152
153 Path to TLS certificate file, defaults to the value of the
154 "MOJO_CERT_FILE" environment variable.
155
156 connect_timeout
157 my $timeout = $ua->connect_timeout;
158 $ua = $ua->connect_timeout(5);
159
160 Maximum amount of time in seconds establishing a connection may take
161 before getting canceled, defaults to the value of the
162 "MOJO_CONNECT_TIMEOUT" environment variable or 10.
163
164 cookie_jar
165 my $cookie_jar = $ua->cookie_jar;
166 $ua = $ua->cookie_jar(Mojo::UserAgent::CookieJar->new);
167
168 Cookie jar to use for requests performed by this user agent, defaults
169 to a Mojo::UserAgent::CookieJar object.
170
171 # Ignore all cookies
172 $ua->cookie_jar->ignore(sub { 1 });
173
174 # Ignore cookies for public suffixes
175 my $ps = IO::Socket::SSL::PublicSuffix->default;
176 $ua->cookie_jar->ignore(sub {
177 my $cookie = shift;
178 return undef unless my $domain = $cookie->domain;
179 return ($ps->public_suffix($domain))[0] eq '';
180 });
181
182 # Add custom cookie to the jar
183 $ua->cookie_jar->add(
184 Mojo::Cookie::Response->new(
185 name => 'foo',
186 value => 'bar',
187 domain => 'mojolicious.org',
188 path => '/perldoc'
189 )
190 );
191
192 inactivity_timeout
193 my $timeout = $ua->inactivity_timeout;
194 $ua = $ua->inactivity_timeout(15);
195
196 Maximum amount of time in seconds a connection can be inactive before
197 getting closed, defaults to the value of the "MOJO_INACTIVITY_TIMEOUT"
198 environment variable or 40. Setting the value to 0 will allow
199 connections to be inactive indefinitely.
200
201 insecure
202 my $bool = $ua->insecure;
203 $ua = $ua->insecure($bool);
204
205 Do not require a valid TLS certificate to access HTTPS/WSS sites,
206 defaults to the value of the "MOJO_INSECURE" environment variable.
207
208 # Disable TLS certificate verification for testing
209 say $ua->insecure(1)->get('https://127.0.0.1:3000')->result->code;
210
211 ioloop
212 my $loop = $ua->ioloop;
213 $ua = $ua->ioloop(Mojo::IOLoop->new);
214
215 Event loop object to use for blocking I/O operations, defaults to a
216 Mojo::IOLoop object.
217
218 key
219 my $key = $ua->key;
220 $ua = $ua->key('/etc/tls/client.crt');
221
222 Path to TLS key file, defaults to the value of the "MOJO_KEY_FILE"
223 environment variable.
224
225 local_address
226 my $address = $ua->local_address;
227 $ua = $ua->local_address('127.0.0.1');
228
229 Local address to bind to.
230
231 max_connections
232 my $max = $ua->max_connections;
233 $ua = $ua->max_connections(5);
234
235 Maximum number of keep-alive connections that the user agent will
236 retain before it starts closing the oldest ones, defaults to 5. Setting
237 the value to 0 will prevent any connections from being kept alive.
238
239 max_redirects
240 my $max = $ua->max_redirects;
241 $ua = $ua->max_redirects(3);
242
243 Maximum number of redirects the user agent will follow before it fails,
244 defaults to the value of the "MOJO_MAX_REDIRECTS" environment variable
245 or 0.
246
247 max_response_size
248 my $max = $ua->max_response_size;
249 $ua = $ua->max_response_size(16777216);
250
251 Maximum response size in bytes, defaults to the value of
252 "max_message_size" in Mojo::Message::Response. Setting the value to 0
253 will allow responses of indefinite size. Note that increasing this
254 value can also drastically increase memory usage, should you for
255 example attempt to parse an excessively large response body with the
256 methods "dom" in Mojo::Message or "json" in Mojo::Message.
257
258 proxy
259 my $proxy = $ua->proxy;
260 $ua = $ua->proxy(Mojo::UserAgent::Proxy->new);
261
262 Proxy manager, defaults to a Mojo::UserAgent::Proxy object.
263
264 # Detect proxy servers from environment
265 $ua->proxy->detect;
266
267 # Manually configure HTTP proxy (using CONNECT for HTTPS/WebSockets)
268 $ua->proxy->http('http://127.0.0.1:8080')->https('http://127.0.0.1:8080');
269
270 # Manually configure Tor (SOCKS5)
271 $ua->proxy->http('socks://127.0.0.1:9050')->https('socks://127.0.0.1:9050');
272
273 # Manually configure UNIX domain socket (using CONNECT for HTTPS/WebSockets)
274 $ua->proxy->http('http+unix://%2Ftmp%2Fproxy.sock') ->https('http+unix://%2Ftmp%2Fproxy.sock');
275
276 request_timeout
277 my $timeout = $ua->request_timeout;
278 $ua = $ua->request_timeout(5);
279
280 Maximum amount of time in seconds establishing a connection, sending
281 the request and receiving a whole response may take before getting
282 canceled, defaults to the value of the "MOJO_REQUEST_TIMEOUT"
283 environment variable or 0. Setting the value to 0 will allow the user
284 agent to wait indefinitely. The timeout will reset for every followed
285 redirect.
286
287 # Total limit of 5 seconds, of which 3 seconds may be spent connecting
288 $ua->max_redirects(0)->connect_timeout(3)->request_timeout(5);
289
290 server
291 my $server = $ua->server;
292 $ua = $ua->server(Mojo::UserAgent::Server->new);
293
294 Application server relative URLs will be processed with, defaults to a
295 Mojo::UserAgent::Server object.
296
297 # Mock web service
298 $ua->server->app(Mojolicious->new);
299 $ua->server->app->routes->get('/time' => sub {
300 my $c = shift;
301 $c->render(json => {now => time});
302 });
303 my $time = $ua->get('/time')->result->json->{now};
304
305 # Change log level
306 $ua->server->app->log->level('fatal');
307
308 # Port currently used for processing relative URLs blocking
309 say $ua->server->url->port;
310
311 # Port currently used for processing relative URLs non-blocking
312 say $ua->server->nb_url->port;
313
314 transactor
315 my $t = $ua->transactor;
316 $ua = $ua->transactor(Mojo::UserAgent::Transactor->new);
317
318 Transaction builder, defaults to a Mojo::UserAgent::Transactor object.
319
320 # Change name of user agent
321 $ua->transactor->name('MyUA 1.0');
322
323 # Disable compression
324 $ua->transactor->compressed(0);
325
327 Mojo::UserAgent inherits all methods from Mojo::EventEmitter and
328 implements the following new ones.
329
330 build_tx
331 my $tx = $ua->build_tx(GET => 'example.com');
332 my $tx = $ua->build_tx(PUT => 'http://example.com' => {Accept => '*/*'} => 'Content!');
333 my $tx = $ua->build_tx(PUT => 'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
334 my $tx = $ua->build_tx(PUT => 'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
335
336 Generate Mojo::Transaction::HTTP object with "tx" in
337 Mojo::UserAgent::Transactor.
338
339 # Request with custom cookie
340 my $tx = $ua->build_tx(GET => 'https://example.com/account');
341 $tx->req->cookies({name => 'user', value => 'sri'});
342 $tx = $ua->start($tx);
343
344 # Deactivate gzip compression
345 my $tx = $ua->build_tx(GET => 'example.com');
346 $tx->req->headers->remove('Accept-Encoding');
347 $tx = $ua->start($tx);
348
349 # Interrupt response by raising an error
350 my $tx = $ua->build_tx(GET => 'http://example.com');
351 $tx->res->on(progress => sub {
352 my $res = shift;
353 return unless my $server = $res->headers->server;
354 $res->error({message => 'Oh noes, it is IIS!'}) if $server =~ /IIS/;
355 });
356 $tx = $ua->start($tx);
357
358 build_websocket_tx
359 my $tx = $ua->build_websocket_tx('ws://example.com');
360 my $tx = $ua->build_websocket_tx( 'ws://example.com' => {DNT => 1} => ['v1.proto']);
361
362 Generate Mojo::Transaction::HTTP object with "websocket" in
363 Mojo::UserAgent::Transactor.
364
365 # Custom WebSocket handshake with cookie
366 my $tx = $ua->build_websocket_tx('wss://example.com/echo');
367 $tx->req->cookies({name => 'user', value => 'sri'});
368 $ua->start($tx => sub {
369 my ($ua, $tx) = @_;
370 say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
371 $tx->on(message => sub {
372 my ($tx, $msg) = @_;
373 say "WebSocket message: $msg";
374 $tx->finish;
375 });
376 $tx->send('Hi!');
377 });
378 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
379
380 delete
381 my $tx = $ua->delete('example.com');
382 my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => 'Content!');
383 my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
384 my $tx = $ua->delete('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
385
386 Perform blocking "DELETE" request and return resulting
387 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
388 Mojo::UserAgent::Transactor (except for the "DELETE" method, which is
389 implied). You can also append a callback to perform requests non-
390 blocking.
391
392 $ua->delete('http://example.com' => json => {a => 'b'} => sub {
393 my ($ua, $tx) = @_;
394 say $tx->result->body;
395 });
396 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
397
398 delete_p
399 my $promise = $ua->delete_p('http://example.com');
400
401 Same as "delete", but performs all requests non-blocking and returns a
402 Mojo::Promise object instead of accepting a callback.
403
404 $ua->delete_p('http://example.com' => json => {a => 'b'})->then(sub {
405 my $tx = shift;
406 say $tx->result->body;
407 })->catch(sub {
408 my $err = shift;
409 warn "Connection error: $err";
410 })->wait;
411
412 get
413 my $tx = $ua->get('example.com');
414 my $tx = $ua->get('http://example.com' => {Accept => '*/*'} => 'Content!');
415 my $tx = $ua->get(
416 'http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
417 my $tx = $ua->get(
418 'http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
419
420 Perform blocking "GET" request and return resulting
421 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
422 Mojo::UserAgent::Transactor (except for the "GET" method, which is
423 implied). You can also append a callback to perform requests non-
424 blocking.
425
426 $ua->get('http://example.com' => json => {a => 'b'} => sub {
427 my ($ua, $tx) = @_;
428 say $tx->result->body;
429 });
430 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
431
432 get_p
433 my $promise = $ua->get_p('http://example.com');
434
435 Same as "get", but performs all requests non-blocking and returns a
436 Mojo::Promise object instead of accepting a callback.
437
438 $ua->get_p('http://example.com' => json => {a => 'b'})->then(sub {
439 my $tx = shift;
440 say $tx->result->body;
441 })->catch(sub {
442 my $err = shift;
443 warn "Connection error: $err";
444 })->wait;
445
446 head
447 my $tx = $ua->head('example.com');
448 my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => 'Content!');
449 my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
450 my $tx = $ua->head('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
451
452 Perform blocking "HEAD" request and return resulting
453 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
454 Mojo::UserAgent::Transactor (except for the "HEAD" method, which is
455 implied). You can also append a callback to perform requests non-
456 blocking.
457
458 $ua->head('http://example.com' => json => {a => 'b'} => sub {
459 my ($ua, $tx) = @_;
460 say $tx->result->body;
461 });
462 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
463
464 head_p
465 my $promise = $ua->head_p('http://example.com');
466
467 Same as "head", but performs all requests non-blocking and returns a
468 Mojo::Promise object instead of accepting a callback.
469
470 $ua->head_p('http://example.com' => json => {a => 'b'})->then(sub {
471 my $tx = shift;
472 say $tx->result->body;
473 })->catch(sub {
474 my $err = shift;
475 warn "Connection error: $err";
476 })->wait;
477
478 options
479 my $tx = $ua->options('example.com');
480 my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => 'Content!');
481 my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
482 my $tx = $ua->options('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
483
484 Perform blocking "OPTIONS" request and return resulting
485 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
486 Mojo::UserAgent::Transactor (except for the "OPTIONS" method, which is
487 implied). You can also append a callback to perform requests non-
488 blocking.
489
490 $ua->options('http://example.com' => json => {a => 'b'} => sub {
491 my ($ua, $tx) = @_;
492 say $tx->result->body;
493 });
494 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
495
496 options_p
497 my $promise = $ua->options_p('http://example.com');
498
499 Same as "options", but performs all requests non-blocking and returns a
500 Mojo::Promise object instead of accepting a callback.
501
502 $ua->options_p('http://example.com' => json => {a => 'b'})->then(sub {
503 my $tx = shift;
504 say $tx->result->body;
505 })->catch(sub {
506 my $err = shift;
507 warn "Connection error: $err";
508 })->wait;
509
510 patch
511 my $tx = $ua->patch('example.com');
512 my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => 'Content!');
513 my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
514 my $tx = $ua->patch('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
515
516 Perform blocking "PATCH" request and return resulting
517 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
518 Mojo::UserAgent::Transactor (except for the "PATCH" method, which is
519 implied). You can also append a callback to perform requests non-
520 blocking.
521
522 $ua->patch('http://example.com' => json => {a => 'b'} => sub {
523 my ($ua, $tx) = @_;
524 say $tx->result->body;
525 });
526 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
527
528 patch_p
529 my $promise = $ua->patch_p('http://example.com');
530
531 Same as "patch", but performs all requests non-blocking and returns a
532 Mojo::Promise object instead of accepting a callback.
533
534 $ua->patch_p('http://example.com' => json => {a => 'b'})->then(sub {
535 my $tx = shift;
536 say $tx->result->body;
537 })->catch(sub {
538 my $err = shift;
539 warn "Connection error: $err";
540 })->wait;
541
542 post
543 my $tx = $ua->post('example.com');
544 my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => 'Content!');
545 my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
546 my $tx = $ua->post('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
547
548 Perform blocking "POST" request and return resulting
549 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
550 Mojo::UserAgent::Transactor (except for the "POST" method, which is
551 implied). You can also append a callback to perform requests non-
552 blocking.
553
554 $ua->post('http://example.com' => json => {a => 'b'} => sub {
555 my ($ua, $tx) = @_;
556 say $tx->result->body;
557 });
558 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
559
560 post_p
561 my $promise = $ua->post_p('http://example.com');
562
563 Same as "post", but performs all requests non-blocking and returns a
564 Mojo::Promise object instead of accepting a callback.
565
566 $ua->post_p('http://example.com' => json => {a => 'b'})->then(sub {
567 my $tx = shift;
568 say $tx->result->body;
569 })->catch(sub {
570 my $err = shift;
571 warn "Connection error: $err";
572 })->wait;
573
574 put
575 my $tx = $ua->put('example.com');
576 my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => 'Content!');
577 my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => form => {a => 'b'});
578 my $tx = $ua->put('http://example.com' => {Accept => '*/*'} => json => {a => 'b'});
579
580 Perform blocking "PUT" request and return resulting
581 Mojo::Transaction::HTTP object, takes the same arguments as "tx" in
582 Mojo::UserAgent::Transactor (except for the "PUT" method, which is
583 implied). You can also append a callback to perform requests non-
584 blocking.
585
586 $ua->put('http://example.com' => json => {a => 'b'} => sub {
587 my ($ua, $tx) = @_;
588 say $tx->result->body;
589 });
590 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
591
592 put_p
593 my $promise = $ua->put_p('http://example.com');
594
595 Same as "put", but performs all requests non-blocking and returns a
596 Mojo::Promise object instead of accepting a callback.
597
598 $ua->put_p('http://example.com' => json => {a => 'b'})->then(sub {
599 my $tx = shift;
600 say $tx->result->body;
601 })->catch(sub {
602 my $err = shift;
603 warn "Connection error: $err";
604 })->wait;
605
606 start
607 my $tx = $ua->start(Mojo::Transaction::HTTP->new);
608
609 Perform blocking request for a custom Mojo::Transaction::HTTP object,
610 which can be prepared manually or with "build_tx". You can also append
611 a callback to perform requests non-blocking.
612
613 my $tx = $ua->build_tx(GET => 'http://example.com');
614 $ua->start($tx => sub {
615 my ($ua, $tx) = @_;
616 say $tx->result->body;
617 });
618 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
619
620 start_p
621 my $promise = $ua->start_p(Mojo::Transaction::HTTP->new);
622
623 Same as "start", but performs all requests non-blocking and returns a
624 Mojo::Promise object instead of accepting a callback.
625
626 my $tx = $ua->build_tx(GET => 'http://example.com');
627 $ua->start_p($tx)->then(sub {
628 my $tx = shift;
629 say $tx->result->body;
630 })->catch(sub {
631 my $err = shift;
632 warn "Connection error: $err";
633 })->wait;
634
635 websocket
636 $ua->websocket('ws://example.com' => sub {...});
637 $ua->websocket('ws://example.com' => {DNT => 1} => ['v1.proto'] => sub {...});
638
639 Open a non-blocking WebSocket connection with transparent handshake,
640 takes the same arguments as "websocket" in Mojo::UserAgent::Transactor.
641 The callback will receive either a Mojo::Transaction::WebSocket or
642 Mojo::Transaction::HTTP object, depending on if the handshake was
643 successful.
644
645 $ua->websocket('wss://example.com/echo' => ['v1.proto'] => sub {
646 my ($ua, $tx) = @_;
647 say 'WebSocket handshake failed!' and return unless $tx->is_websocket;
648 say 'Subprotocol negotiation failed!' and return unless $tx->protocol;
649 $tx->on(finish => sub {
650 my ($tx, $code, $reason) = @_;
651 say "WebSocket closed with status $code.";
652 });
653 $tx->on(message => sub {
654 my ($tx, $msg) = @_;
655 say "WebSocket message: $msg";
656 $tx->finish;
657 });
658 $tx->send('Hi!');
659 });
660 Mojo::IOLoop->start unless Mojo::IOLoop->is_running;
661
662 You can activate "permessage-deflate" compression by setting the
663 "Sec-WebSocket-Extensions" header, this can result in much better
664 performance, but also increases memory usage by up to 300KiB per
665 connection.
666
667 $ua->websocket('ws://example.com/foo' => {
668 'Sec-WebSocket-Extensions' => 'permessage-deflate'
669 } => sub {...});
670
671 websocket_p
672 my $promise = $ua->websocket_p('ws://example.com');
673
674 Same as "websocket", but returns a Mojo::Promise object instead of
675 accepting a callback.
676
677 $ua->websocket_p('wss://example.com/echo')->then(sub {
678 my $tx = shift;
679 my $promise = Mojo::Promise->new;
680 $tx->on(finish => sub { $promise->resolve });
681 $tx->on(message => sub {
682 my ($tx, $msg) = @_;
683 say "WebSocket message: $msg";
684 $tx->finish;
685 });
686 $tx->send('Hi!');
687 return $promise;
688 })->catch(sub {
689 my $err = shift;
690 warn "WebSocket error: $err";
691 })->wait;
692
694 You can set the "MOJO_CLIENT_DEBUG" environment variable to get some
695 advanced diagnostics information printed to "STDERR".
696
697 MOJO_CLIENT_DEBUG=1
698
700 Mojolicious, Mojolicious::Guides, <https://mojolicious.org>.
701
702
703
704perl v5.32.0 2020-07-28 Mojo::UserAgent(3)