[英]How to make the post request in BOX API using LWP::UserAgent?
[英]How can I make a JSON POST request with LWP?
如果您尝试登录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
这样做,但如果可用的话,我会更喜欢更高级别的东西。
您需要手动构建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 );
只需创建一个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.
该页面只是使用“匿名”(无名称)输入,恰好是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));
如果您真的想使用WWW :: Mechanize,可以在发布之前设置标题'content-type'
$mech->add_header(
'content-type' => 'application/json'
);
$mech->post($uri, Content => $json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.