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