簡體   English   中英

如何使用 HTTP 請求 (Perl) POST 內容

[英]How to POST content with an HTTP Request (Perl)

use LWP::UserAgent;
use Data::Dumper;

my $ua = new LWP::UserAgent;
$ua->agent("AgentName/0.1 " . $ua->agent);
my $req = new HTTP::Request POST => 'http://example.com';
$req->content('port=8', 'target=64'); #problem
my $res = $ua->request($req);

print Dumper($res->content);

如何使用 $req->content 發送多條內容? $req->content 期望什么樣的數據?

它只發送最后一個。

編輯:

發現如果我將它格式化為 'port=8&target=64' 它可以工作。 有沒有更好的辦法?

my $ua      = LWP::UserAgent->new(); 
my $request = POST( $url, [ 'port' => 8, 'target' => 64 ] ); 
my $content = $ua->request($request)->as_string(); 

給出的答案對我不起作用。 我仍然遇到與 OP 相同的問題。

LWP::UserAgent的文檔需要散列或數組引用。

這有效:

my $url = 'https://www.google.com/recaptcha/api/siteverify';
my $ua      = LWP::UserAgent->new(); 

my %form;
$form{'secret'}='xxxxxxxxxxxxxxxxxxxxxxx';
$form{'response'}=$captchaResponse;

my $response = $ua->post( $url, \%form ); 
my $content = $response->as_string();

一起使用 LWP::UserAgent 和 HTTP::Request 因為它也很常見,如果不是更頻繁的實踐,我幾乎沒有感到困惑,除了 json 之外,標准 POST 和 GET / request 幾乎沒有被討論過,因為它們很大大多數使用。

郵政

    my $ua  = LWP::UserAgent->new();
    my $req = new HTTP::Request( 
       'POST' => "http://url/path", 
       ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'],
       'par1=par1value&par2=par2value'
    );
    $ua->request($req);

同樣對於 GET

    my $ua  = LWP::UserAgent->new();
    my $req = new HTTP::Request( 
       'GET' => "http://url/path", 
       ['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'],
       'par1=par1value&par2=par2value' # or I presume attaching the query string directly to the url
    );
    $ua->request($req);

另一種格式形式,其中前兩個參數(method 和 url)沒有融合成一個,不像前面那樣,而是分開

my $request = HTTP::Request->new( 'POST', $url, [ parameter1 => 'parameter1Value' ] );
request->header( 'Content-Type' => 'application/json' )

有一個類似的問題,但只是關於 LWP 和 Json,但它可能只能通過同時使用 LWP 和 HTTP::Request 來完成,正如該問題選擇的答案所建議的那樣,並且 POST 和 GET 在那里丟失,但它可能不會已經很明顯

如何使用 LWP 發出 JSON POST 請求?

注意:我也特地發布了這個,因為即使在文檔https://metacpan.org/pod/HTTP::Request中也沒有提到 POST/GET 的具體/簡潔用法

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM