32

如果您尝试在https://orbit.theplanet.com/Login.aspx?url=/Default.aspx登录(使用任何用户名/密码组合),您可以看到登录凭据作为非传统设置发送POST 数据:只是一个孤立的 JSON 字符串,没有正常的键=值对。

具体来说,而不是:

username=foo&password=bar

甚至类似:

json={"username":"foo","password":"bar"}

很简单:

{"username":"foo","password":"bar"}

LWP是否可以使用或替代模块执行此类请求?我准备这样做,IO::Socket但如果可以的话,我更喜欢更高级的东西。

4

4 回答 4

78

您需要手动构建 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 );

然后你可以使用 LWP 执行请求:

my $lwp = LWP::UserAgent->new;
$lwp->request( $req );
于 2010-11-16T21:48:12.577 回答
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.
于 2010-11-16T21:45:54.403 回答
13

该页面仅使用“匿名”(无名称)输入,恰好是 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());
}

或者,您也可以对 JSON 输入使用哈希:

use JSON::XS qw(encode_json);

...

my %json;
$json{username} = "foo";
$json{password} = "bar";

...

$response = $ua->post($url, Content => encode_json(\%json));
于 2015-08-04T16:15:16.273 回答
1

如果你真的想使用 WWW::Mechanize 你可以在发布前设置标题'content-type'

$mech->add_header( 
'content-type' => 'application/json'
);

$mech->post($uri, Content => $json);
于 2014-12-10T00:46:31.143 回答