![](/img/trans.png)
[英]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.