Mojo::UserAgent - 非阻塞的 HTTP I/O and WebSocket UA

摘要

  use Mojo::UserAgent;
  my $ua = Mojo::UserAgent->new;

  # Say hello to the Unicode snowman with "Do Not Track" header
  say $ua->get('www.☃.net?hello=there' => {DNT => 1})->res->body;

  # Form POST with exception handling
  my $tx = $ua->post_form('search.cpan.org/search' => {q => 'mojo'});
  if (my $res = $tx->success) { say $res->body }
  else {
    my ($err, $code) = $tx->error;
    say $code ? "$code response: $err" : "Connection error: $err";
  }

  # Quick JSON API request with Basic authentication
  say $ua->get('https://sri:s3cret@search.twitter.com/search.json?q=perl')
    ->res->json('/results/0/text');

  # Extract data from HTML and XML resources
  say $ua->get('mojolicio.us')->res->dom->html->head->title->text;

  # Scrape the latest headlines from a news site
  say $ua->max_redirects(5)->get('www.reddit.com/r/perl/')
    ->res->dom('p.title > a.title')->pluck('text')->shuffle;

  # IPv6 PUT request with content
  my $tx
    = $ua->put('[::1]:3000' => {'Content-Type' => 'text/plain'} => 'Hello!');

  # Grab the latest Mojolicious release :)
  $ua->max_redirects(5)->get('latest.mojolicio.us')
    ->res->content->asset->move_to('/Users/sri/mojo.tar.gz');

  # TLS certificate authentication and JSON POST
  my $tx = $ua->cert('tls.crt')->key('tls.key')
    ->post_json('https://mojolicio.us' => {top => 'secret'});

  # Custom JSON PUT request
  my $tx = $ua->build_json_tx('http://mojolicious/foo' => {hi => 'there'});
  $tx->req->method('PUT');
  say $ua->start($tx)->res->body;

  # Blocking parallel requests (does not work inside a running event loop)
  my $delay = Mojo::IOLoop->delay;
  for my $url ('mojolicio.us', 'cpan.org') {
    $delay->begin;
    $ua->get($url => sub {
      my ($ua, $tx) = @_;
      $delay->end($tx->res->dom->at('title')->text);
    });
  }
  my @titles = $delay->wait;

  # Non-blocking parallel requests (does work inside a running event loop)
  my $delay = Mojo::IOLoop->delay(sub {
    my ($delay, @titles) = @_;
    ...
  });
  for my $url ('mojolicio.us', 'cpan.org') {
    $delay->begin;
    $ua->get($url => sub {
      my ($ua, $tx) = @_;
      $delay->end($tx->res->dom->at('title')->text);
    });
  }
  $delay->wait unless Mojo::IOLoop->is_running;

  # Non-blocking WebSocket connection
  $ua->websocket('ws://websockets.org:8787' => sub {
    my ($ua, $tx) = @_;
    $tx->on(finish  => sub { say 'WebSocket closed.' });
    $tx->on(message => sub {
      my ($tx, $msg) = @_;
      say "WebSocket message: $msg";
      $tx->finish;
    });
    $tx->send('hi there!');
  });
  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;

EVENTS

Mojo::UserAgent 事件:

error

  $ua->on(error => sub {
    my ($ua, $err) = @_;
    say "This looks bad: $err";
  });

如果一个错误关联到一个transaction,ua的错误信息将不会产生。

start

无论何时一个新的tx开始,都将运行start事件,这将自动准备connect请求的代理,redirects.

$ua->on(start => sub {
    my ($ua, $tx) = @_;
    $tx->req->headers->header('X-Bender' => 'Bite my shiny metal ass!');
});

ATTRIBUTES

Mojo::UserAgent属性如下:

ca

my $ca = $ua->ca;
$ua    = $ua->ca('/etc/tls/ca.crt');

Path to TLS certificate authority file, defaults to the value of the MOJO_CA_FILE environment variable. Also activates hostname verification.

# Show certificate authorities for debugging
IO::Socket::SSL::set_ctx_defaults(
    SSL_verify_callback => sub { say "Authority: $_[2]" and return $_[0] });

cert

my $cert = $ua->cert;
$ua      = $ua->cert('/etc/tls/client.crt');

Path to TLS certificate file, defaults to the value of the MOJO_CERT_FILE environment variable.

connect_timeout

my $timeout = $ua->connect_timeout;
$ua         = $ua->connect_timeout(5);

最大链接超时单位秒,缺省是10在MOJO_CONNECT_TIMEOUT environment 环境变量中设置

cookie_jar

my $cookie_jar = $ua->cookie_jar;
$ua            = $ua->cookie_jar(Mojo::UserAgent::CookieJar->new);

Cookie jar 在request中使用,缺省是Mojo::UserAgent::CookieJar  object.

# 禁用cookie
$ua->cookie_jar(0);

http_proxy

my $proxy = $ua->http_proxy;
$ua       = $ua->http_proxy('http://sri:secret@127.0.0.1:8080');

  HTTP and WebSocket 请求 代理Server.

https_proxy

my $proxy = $ua->https_proxy;
$ua       = $ua->https_proxy('http://sri:secret@127.0.0.1:8080');

未完持续中….

posted @ 2013-02-08 16:37  新闻官  阅读(923)  评论(0编辑  收藏  举报