10. Basic Usage
use Mojo::UserAgent;
my $ua = Mojo::UserAgent->new;
my $tx = $ua->get(‘URL’ => Header =>BODY);
if ( my $res = $tx->success) {
# $res をつかってごにょごにょ
} else {
my ($msg, $code) = $tx->error;
die “$msg: $code”;
}
11. Get
my $tx = $ua->post(‘http://www.example.com/login’, form
=> { username => ‘scott’, password => ‘tiger’ });
if ( my $res = $tx->success ) {
for my $cookie (map {$_->res->cookies} @{$tx-
>redirects}) {
if ( $cookie->name eq ‘PHPSESSID’ ) {
# ごにょごにょ
}
}
}
12. Put
my $cookie = Mojo::Cookie::Response->new;
$cookie->name(‘PHPSESSID’);
$cookie->value($phpsessid);
$cookie->path(‘/’);
$ua->cookie_jar->add($cookie);
13. Scraping
my $coll = $res->dom(‘section#illust_list ul li a.work’);
# $coll … Mojo::Collection
$coll->each(sub {
my ($e, $count) = @_;
my $title = $e->find(‘h1’)->first->text;
my $img_url = $e->find(‘img’)->first->attr(‘src’);
# ごにょごにょ
});
14. JSON
my $tx = $ua->post(‘...’, json => {loren => ‘ipsum’});
# assuming json in response:
# { “result”: “ok”, “body”: {“title”: “hogehoge”} }
if (my $res = $tx->success) {
if ( $res->json(‘/result’) eq “ok” ) {
say $res->json(‘/body/title’);
}
}
15. ByteStream
use Mojo::ByteStream;
my $tx = $ua->get(‘http://.../foo.jpg’);
if ( my $res = $tx->success ) {
my $bs = Mojo::ByteStream->new($res->body);
$bs->spurt(‘/tmp/foo.jpg’);
say “MD5: “, $bs->md5_sum;
}