- 論壇徽章:
- 0
|
LWP中文FAQ
若有變動或補充仙子會即時更新
1. 如何快速GET一個頁面?
- use LWP::Simple;
- my $doc = get 'http://www.example.com/';
復制代碼
2. 標準的HTTP請求過程?
- use LWP::UserAgent;
- my $ua = LWP::UserAgent->new;
- my $req = HTTP::Request->new(GET => 'http://www.example.com/');
- my $res = $ua->request($req);
- if ($res->is_success) {
- print $res->as_string;
- }else {
- print "Failed: ", $res->status_line, "\n";
- }
復制代碼
3. 如何得到HTTP響應狀態碼?
4. 如何得到HTTP響應的完整內容?
5. 如何得到HTTP響應的HTML解碼后的內容?
- print $res->decoded_content;
復制代碼
6. 如何POST數據?
- use LWP::UserAgent;
- my $ua = LWP::UserAgent->new;
- my $req = HTTP::Request->new(POST => 'http://www.example.com/');
- $req->content_type('application/x-www-form-urlencoded');
- $req->content('key1=value1&key2=value2');
- my $res = $ua->request($req);
- print $res->as_string;
復制代碼
7. 如何接受Cookie?
- use LWP::UserAgent;
- use HTTP::Cookies;
- my $ua = LWP::UserAgent->new;
- $ua->cookie_jar(HTTP::Cookies->new(file => "lwpcookies.txt",
- autosave => 1));
- my $req = HTTP::Request->new(GET => "http://www.example.com/");
- my $res = $ua->request($req);
- print $res->status_line;
復制代碼
8. 如何在請求里發送指定的Cookie?
- use LWP::UserAgent;
- my $ua = LWP::UserAgent->new;
- my $req = HTTP::Request->new(GET => 'http://www.example.com/');
- $req->header('Cookie' => "key1=value1;key2=value2");
- my $res = $ua->request($req);
- print $res->status_line;
復制代碼
9. 如何訪問需要身份驗證的網站(basic auth)?
- use LWP::UserAgent;
- my $ua = LWP::UserAgent->new;
- my $req = HTTP::Request->new(GET => 'http://www.example.com/');
- my $req->authorization_basic('user', 'password');
- my $res = $ua->request($req);
- print $res->as_string;
復制代碼
10. 如何指定UserAgent的超時時間和版本?
- my $ua = LWP::UserAgent->new;
- $ua->timeout(5);
- $ua->agent("Mozilla/8.0");
復制代碼
11. 如何讓UserAgent不follow重定向?
參數表示跟隨重定向的層數,0表示不跟隨重定向。
12. 如果機器有多個IP,如何指定UserAgent使用哪個IP訪問網絡?
- $ua->local_address('1.2.3.4');
復制代碼
13. 直接使用IP訪問網站,為什么會失?
那是因為沒有加上Host頭部,虛擬主機識別不出你的請求。
在構造請求時,請加上Host頭部:
- my $req = HTTP::Request->new(GET => "1.2.3.4");
- $req->header('Accept' => 'text/html',
- 'Host' => 'www.example.com');
復制代碼 |
|