perl 发起网络请求

Docs

get

#!/usr/bin/perl
use v5.26;
use Encode qw(decode encode);
use autodie;
use LWP::Simple qw(get);

my $res = get( "http://localhost:3000/a?name=ajanuw&age=12&age=14" );
say $res;

get2

#!/usr/bin/perl
use v5.26;
use autodie;
use warnings;
use Encode qw(encode_utf8);
use LWP::Simple;
use URI::URL;

my $url = url('http://localhost:3000/a');
$url->query_form(name => 'ajanuw', age => 12);
my $content = get($url);
say $content;

get 3

#!/use/bin/perl;
use warnings;
use autodie;
use v5.26;
use Mojo::UserAgent;

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

say $ua->get(
  'http://localhost:5000/get-json' => { Accept => '*/*' } => form => { id => 2 }
)->res->body;

say $ua->get('http://localhost:3000/get-info')->res->body;
say $ua->get('http://localhost:3000/get-info')->res->json->{name}; // resData.name

my $res = $ua->get('http://localhost:3000/get-info')->res;
say $res->json("/name");

get 4

#!/use/bin/perl;
use warnings;
use autodie;
use v5.26;
use Mojo::UserAgent;

my $ua = Mojo::UserAgent->new;
say $ua->get('http://localhost:3000/get-page')->res->dom->find('p[id="msg"]')->[0];

say $ua->get('http://localhost:3000/get-page')->res->dom->at('#msg'); // 使用css选择器

post

#!/usr/bin/perl
use v5.26;
use autodie;
use  LWP::UserAgent;
use Encode qw(encode_utf8);
use HTTP::Request ();
use JSON::MaybeXS qw(encode_json decode_json);

my $r = HTTP::Request->new('POST', "http://localhost:3000/post", [
    'Content-Type' => 'application/x-www-form-urlencoded'
], "name=ajanuw&age=12&age=140");

my $res = LWP::UserAgent->new()->request($r);
say $res;

post2

#!/usr/bin/perl
use v5.26;
use autodie;
use LWP::UserAgent;
use HTTP::Request::Common qw(POST);
use Encode qw(encode_utf8);

my $ua = LWP::UserAgent->new(); 
my $req = POST 'http://localhost:3000/post',
                   [ name => 'ajanuw', age => 12, age => 14 ];
my $content = $ua->request($req)->as_string;
say $content;
posted @ 2018-08-28 16:30  Ajanuw  阅读(397)  评论(0)    收藏  举报