Ric*_*ões 28 perl json http-post lwp
如果您尝试登录https://orbit.theplanet.com/Login.aspx?url=/Default.aspx(使用任何用户名/密码组合),您可以看到登录凭据是作为非传统集发送的POST数据:只是一个寂寞的JSON字符串,没有普通的键=值对.
具体而言,而不是:
username=foo&password=bar
Run Code Online (Sandbox Code Playgroud)
甚至是这样的:
json={"username":"foo","password":"bar"}
Run Code Online (Sandbox Code Playgroud)
简单来说:
{"username":"foo","password":"bar"}
Run Code Online (Sandbox Code Playgroud)
是否可以LWP使用替代模块执行此类请求?我准备这样做,IO::Socket但如果有的话,我会更喜欢更高级别的东西.
fri*_*edo 70
您需要手动构建HTTP请求并将其传递给LWP.像下面这样的东西应该这样做:
my $uri = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
my $json = '{"username":"foo","password":"bar"}';
my $req = HTTP::Request->new( 'POST', $uri );
$req->header( 'Content-Type' => 'application/json' );
$req->content( $json );
Run Code Online (Sandbox Code Playgroud)
然后你可以用LWP执行请求:
my $lwp = LWP::UserAgent->new;
$lwp->request( $req );
Run Code Online (Sandbox Code Playgroud)
hob*_*bbs 15
只需创建一个POST请求,并将其作为正文,并将其提供给LWP.
my $req = HTTP::Request->new(POST => $url);
$req->content_type('application/json');
$req->content($json);
my $ua = LWP::UserAgent->new; # You might want some options here
my $res = $ua->request($req);
# $res is an HTTP::Response, see the usual LWP docs.
Run Code Online (Sandbox Code Playgroud)
该页面只是使用"匿名"(无名称)输入,恰好是JSON格式.
您应该能够使用$ ua-> post($ url,...,Content => $ content),而后者又使用HTTP :: Request :: Common中的POST()函数.
use LWP::UserAgent;
my $url = 'https://orbit.theplanet.com/Login.aspx?url=/Default.aspx';
my $json = '{"username": "foo", "password": "bar"}';
my $ua = new LWP::UserAgent();
$response = $ua->post($url, Content => $json);
if ( $response->is_success() ) {
print("SUCCESSFUL LOGIN!\n");
}
else {
print("ERROR: " . $response->status_line());
}
Run Code Online (Sandbox Code Playgroud)
或者,您也可以使用哈希作为JSON输入:
use JSON::XS qw(encode_json);
...
my %json;
$json{username} = "foo";
$json{password} = "bar";
...
$response = $ua->post($url, Content => encode_json(\%json));
Run Code Online (Sandbox Code Playgroud)