Работа с LWP::UserAgent


Работа с LWP::UserAgent
Основные вопросы и решения, связанные с модулем LWP (Работа с HTTP/HTTPS)

Как получить текстовый файл, используя http или ftp?

 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://www.yahoo.com/';
 my $res = LWP::UserAgent->new->request(new HTTP::Request GET => $URL);
 print header, $res->is_success ? $res->content : $res->status_line;

Как скачать себе из сети файл jpeg/gif/bmp


 use LWP::UserAgent;
 use CGI qw(header -no_debug);
 $URL =
 'http://a100.g.akamaitech.net/7/100/70/0001/www.fool.com/art/new/butts/go99.
 gif';
 my $res = LWP::UserAgent->new->request(new HTTP::Request GET => $URL);
 binmode(STDOUT);
 print $res->is_success ? (header('image/gif'), $res->content)
                        : (header('text/html'), $res->status_line);

Как получить доступ к защищенному паролем файлу?

 BEGIN {
   package RequestAgent;
   use LWP::UserAgent;
   @ISA = qw(LWP::UserAgent);

   sub new { LWP::UserAgent::new(@_); }
   sub get_basic_credentials { return 'user', 'password' }
 }
 use CGI qw(header -no_debug);

 my $res = RequestAgent->new->request(new HTTP::Request GET => $URL);
 print header, $res->is_success ? $res->content : $res->status_line;

Как установить REFERER и другие параметры в HTTP заголовке?

 use LWP::UserAgent;
 use HTTP::Headers;
 use CGI qw(header -no_debug);

 my $URL = 'http://localhost/cgi-bin/hello.cgi';
 my $res = LWP::UserAgent->new->request(
   new HTTP::Request(
     GET => $URL,
     new HTTP::Headers referer => 'http://www.yahoo.com'),
 );
 print header, $res->is_success ? $res->content : $res->status_line;

Как получить определенную часть файла (первые MAXSIZE байт)?

 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://www.yahoo.com/';
 my $MAXSIZE = 1024;

 print header;
 my $res = LWP::UserAgent->new->request(
   new HTTP::Request(GET => $URL), \&callback, $MAXSIZE);

 sub callback { my($data, $response, $protocol) = @_; print $data; die }

Как получать и устанавливать COOKIES (работа с куками)

 use LWP::UserAgent;
 use CGI qw(header -no_debug);
 use HTTP::Cookies;

 my $URL = 'http://mail.yahoo.com/';

 my $ua = new LWP::UserAgent;
 my $res = $ua->request(new HTTP::Request GET => $URL);
 my $cookie_jar = new HTTP::Cookies;
 $cookie_jar->extract_cookies($res);

 print header;
 if ($res->is_success) {
   my $req = new HTTP::Request GET => $URL;
   $cookie_jar->add_cookie_header($req);
   $res = $ua->request($req);
   print $res->is_success ? $res->as_string : $res->status_line;
 } else {
   print $res->status_line;
 }

Как работать с proxy серверами?

 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://www.yahoo.com/';
 my $ua = new LWP::UserAgent;

 $ua->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/');
 $ua->proxy('gopher', 'http://proxy.sn.no:8001/');

 my $res = $ua->request(new HTTP::Request GET => $URL);
 print header, $res->is_success ? $res->content : $res->status_line;

Как определить редирект?

 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://www.yahoo.com/';
 my $res = LWP::UserAgent->new->request(new HTTP::Request GET => $URL);

 print header;
 print $res->request->url if $res->previous->is_redirect;

Как определить данные для запроса методом POST?

 use URI::URL;
 use HTTP::Request;
 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://yahoo.com/?login=mylogin&password=mypassword';
 my $uri = new URI $URL;
 my $method = 'POST';

 my $request;
 if (uc($method) eq 'POST') {
   my $query = $uri->query;
   (my $url = $uri->as_string) =~ s/\?$query$//;
   $request = new HTTP::Request ($method, $url);
   $request->header('Content-Type' => 'application/x-www-form-urlencoded');
   $request->content($query);
 } else {
   $request = new HTTP::Request ($method, $uri->as_string);
 };

 # add Host field as required in HTTP/1.1
 $request->header(Host => $uri->host_port) if $uri->scheme ne 'file';

 my $res = LWP::UserAgent->new->request($request);

 print header, $res->is_success ? $res->content : $res->status_line;

Как загрузить (upload) файл на удаленный сервер?

 use HTTP::Request::Common;
 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://localhost/cgi-bin/survey.cgi';
 my $req = POST $URL,
   Content_Type => 'form-data',
   Content      => 

     name       => 'Paul Kulchenko',
     email      => '[email protected]',
     surveyfile => ['./survey.dat'], # this file will be uploaded
   ];

 my $res = LWP::UserAgent->new->request($req);

 print header, $res->is_success ? $res->content : $res->status_line;

Как работать с защищенному протоколу (https://) ?

#!/usr/bin/perl -w
$test = "http://www.test.ru/account/secure.html";
use HTTP::Request::Common;
use LWP::UserAgent;
use CGI qw(header -no_debug);
$ua = LWP::UserAgent->new();

my $req = POST $test,
                [
        user => 'vovka',
    password => '123321',
                ];

$content = $ua->request($req)->as_string;
#print "content-type: text/html\n\n";
#print $content;
print $req->as_string;

Как получить информацию о файле на удаленном сервере?

 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $url = 'http://yahoo.com/';
 my $res = LWP::UserAgent->new->request(HTTP::Request->new(HEAD => $url));

 print header;

 local $\ = "\n";
 if ($res->is_success) {
   $res->previous &&
   $res->previous->is_redirect and print 'redirected: ', $res->request->url;
   $res->last_modified         and print 'modified: ',
 scalar(localtime($res->last_modified));
   $res->content_length        and print 'size: ', $res->content_length;
 } else {
   print $res->status_line;
 }

Как делать редирект, работающий как при GET, так и при POST?

 use LWP::UserAgent;
 use CGI qw(header -no_debug);

 my $URL = 'http://www.yahoo.com/';
 my $MAXSIZE = 1024;

 local $| = 'non buffered';

 print header;
 my $res = LWP::UserAgent->new->request(
   new HTTP::Request(GET => $URL),
   sub { my($data, $response, $protocol) = @_; print $data }, # <= callback
   $MAXSIZE,
 );


Оценить Статью:  
1   2   3   4   5   6   7   8   9   10    

« Назад
SAPE все усложнил?

MainLink - простая и прибыльная продажа ссылок!

Последние поступления:

Размещена 10 августа 2020 года

Я по ТВ видел, что через 10 лет мы будем жить лучше, чем в Германии...
Я не понял, что это они с Германией сделать хотят?!

читать далее…

ТехЗадание на Землю

Размещена 14 марта 2018 года

Пpоект Genesis (из коpпоpативной пеpеписки)

читать далее…

Шпаргалка по работе с Vim

Размещена 05 декабря 2017 года

Vim довольно мощный редактор, но работа с ним не всегда наглядна.
Например если нужно отредактировать какой-то файл например при помощи crontab, без знания специфики работы с viv никак.

читать далее…

Ошибка: Error: Cannot find a valid baseurl for repo

Размещена 13 сентабря 2017 года

Если возникает ошибка на centos 5 вида
YumRepo Error: All mirror URLs are not using ftp, http[s] or file.
Eg. Invalid release/

читать далее…

Linux Optimization

Размещена 30 июля 2012 года

Prelink

читать далее…