home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / perl_ste.zip / lwpcook.pod < prev    next >
Text File  |  1997-11-17  |  9KB  |  341 lines

  1. =head1 NAME
  2.  
  3. lwpcook - libwww-perl cookbook
  4.  
  5. =head1 DESCRIPTION
  6.  
  7. This document contain some examples that show typical usage of the
  8. libwww-perl library.  You should consult the documentation for the
  9. individual modules for more detail.
  10.  
  11. All examples should be runnable programs. You can, in most cases, test
  12. the code sections by piping the program text directly to perl.
  13.  
  14.  
  15.  
  16. =head1 GET
  17.  
  18. It is very easy to use this library to just fetch documents from the
  19. net.  The LWP::Simple module provides the get() function that return
  20. the document specified by its URL argument:
  21.  
  22.   use LWP::Simple;
  23.   $doc = get 'http://www.sn.no/libwww-perl/';
  24.  
  25. or, as a perl one-liner using the getprint() function:
  26.  
  27.   perl -MLWP::Simple -e 'getprint "http://www.sn.no/libwww-perl/"'
  28.  
  29. or, how about fetching the latest perl by running this:
  30.  
  31.   perl -MLWP::Simple -e '
  32.     getstore "ftp://ftp.sunet.se/pub/lang/perl/CPAN/src/latest.tar.gz",
  33.              "perl.tar.gz"'
  34.  
  35. You will probably first want to find a CPAN site closer to you by
  36. running something like the following command:
  37.  
  38.   perl -MLWP::Simple -e 'getprint "http://www.perl.com/perl/CPAN/CPAN.html"'
  39.  
  40. Enough of this simple stuff!  The LWP object oriented interface gives
  41. you more control over the request sent to the server.  Using this
  42. interface you have full control over headers sent and how you want to
  43. handle the response returned.
  44.  
  45.   use LWP::UserAgent;
  46.   $ua = new LWP::UserAgent;
  47.   $ua->agent("$0/0.1 " . $ua->agent);
  48.   # $ua->agent("Mozilla/5.0") # pretend you are some very new Netscape browser
  49.  
  50.   $req = new HTTP::Request 'GET' => 'http://www.sn.no/libwww-perl';
  51.   $req->header('Accept' => 'text/html');
  52.  
  53.   # send request
  54.   $res = $ua->request($req);
  55.  
  56.   # check the outcome
  57.   if ($res->is_success) {
  58.      print $res->content;
  59.   } else {
  60.      print "Error: " . $res->code . " " . $res->message;
  61.   }
  62.  
  63. The lwp-request program (alias GET) that is distributed with the
  64. library can also be used to fetch documents from WWW servers.
  65.   
  66.  
  67.  
  68. =head1 HEAD
  69.  
  70. If you just want to check if a document is present (i.e. the URL is
  71. valid) try to run code that looks like this:
  72.  
  73.   use LWP::Simple;
  74.  
  75.   if (head($url)) {
  76.      # ok document exists
  77.   }
  78.  
  79. The head() function really returns a list of meta-information about
  80. the document.  The first three values of the list returned are the
  81. document type, the size of the document, and the age of the document.
  82.  
  83. More control over the request or access to all header values returned
  84. require that you use the object oriented interface described for GET
  85. above.  Just s/GET/HEAD/g.
  86.  
  87.  
  88. =head1 POST
  89.  
  90. There is no simple interface for posting data to a WWW server.  You
  91. must use the object oriented interface for this. The most common POST
  92. operation is to access a WWW form application:
  93.  
  94.   use LWP::UserAgent;
  95.   $ua = new LWP::UserAgent;
  96.  
  97.   my $req = new HTTP::Request 'POST','http://www.perl.com/cgi-bin/BugGlimpse';
  98.   $req->content_type('application/x-www-form-urlencoded');
  99.   $req->content('match=www&errors=0');
  100.  
  101.   my $res = $ua->request($req);
  102.   print $res->as_string;
  103.  
  104. You can also use the HTTP::Request::Common module to set up a suitable
  105. POST request message (it handles all the escaping issues) and has a
  106. suitable default for the content_type:
  107.  
  108.   use HTTP::Request::Common qw(POST);
  109.   use LWP::UserAgent;
  110.   $ua = new LWP::UserAgent;
  111.  
  112.   my $req = POST 'http://www.perl.com/cgi-bin/BugGlimpse',
  113.                 [ search => 'www', errors => 0 ];
  114.  
  115.   print $ua->request($req)->as_string;
  116.  
  117. The lwp-request program (alias POST) that is distributed with the
  118. library can also be used for posting data.
  119.  
  120.  
  121.  
  122. =head1 PROXIES
  123.  
  124. Some sites use proxies to go through fire wall machines, or just as
  125. cache in order to improve performance.  Proxies can also be used for
  126. accessing resources through protocols not supported directly (or
  127. supported badly :-) by the libwww-perl library.
  128.  
  129. You should initialize your proxy setting before you start sending
  130. requests:
  131.  
  132.   use LWP::UserAgent;
  133.   $ua = new LWP::UserAgent;
  134.   $ua->env_proxy; # initialize from environment variables
  135.   # or
  136.   $ua->proxy(ftp  => 'http://proxy.myorg.com');
  137.   $ua->proxy(wais => 'http://proxy.myorg.com');
  138.   $ua->no_proxy(qw(no se fi));
  139.  
  140.   my $req = new HTTP::Request 'wais://xxx.com/';
  141.   print $ua->request($req)->as_string;
  142.  
  143. The LWP::Simple interface will call env_proxy() for you automatically.
  144. Applications that use the $ua->env_proxy() method will normally not
  145. use the $ua->proxy() and $ua->no_proxy() methods.
  146.  
  147. Some proxies also require that you send it a username/password in
  148. order to let requests through.  LWP does not support
  149. Proxy-Authorization directly yet, but you should be able to add the
  150. required header manually.
  151.  
  152. Do something like this:
  153.  
  154.  use LWP::UserAgent;
  155.  use MIME::Base64 qw(encode_base64);
  156.  
  157.  $ua = new LWP::UserAgent;
  158.  $ua->proxy(['http', 'ftp'] => 'http://proxy.myorg.com');
  159.  
  160.  $proxy_auth = "Basic " . encode_base64("proxy_user:proxy_password");
  161.  
  162.  $req = new HTTP::Request 'GET',"http://www.perl.com";
  163.  $req->header("Proxy-Authorization" => $proxy_auth);  # This is the key!
  164.  
  165.  $res = $ua->request($req);
  166.  print $res->content if $res->is_success;
  167.  
  168. Replace C<proxy.myorg.com>, C<proxy_user> and
  169. C<proxy_password> with something suitable for your site.
  170.  
  171.  
  172. =head1 ACCESS TO PROTECTED DOCUMENTS
  173.  
  174. Documents protected by basic authorization can easily be accessed
  175. like this:
  176.  
  177.   use LWP::UserAgent;
  178.   $ua = new LWP::UserAgent;
  179.   $req = new HTTP::Request GET => 'http://www.sn.no/secret/';
  180.   $req->authorization_basic('aas', 'mypassword');
  181.   print $ua->request($req)->as_string;
  182.  
  183. The other alternative is to provide a subclass of I<LWP::UserAgent> that
  184. overrides the get_basic_credentials() method. Study the I<lwp-request>
  185. program for an example of this.
  186.  
  187.  
  188. =head1 MIRRORING
  189.  
  190. If you want to mirror documents from a WWW server, then try to run
  191. code similar to this at regular intervals:
  192.  
  193.   use LWP::Simple;
  194.  
  195.   %mirrors = (
  196.      'http://www.sn.no/'             => 'sn.html',
  197.      'http://www.perl.com/'          => 'perl.html',
  198.      'http://www.sn.no/libwww-perl/' => 'lwp.html',
  199.      'gopher://gopher.sn.no/'        => 'gopher.html',
  200.   );
  201.  
  202.   while (($url, $localfile) = each(%mirrors)) {
  203.      mirror($url, $localfile);
  204.   }
  205.  
  206. Or, as a perl one-liner:
  207.  
  208.   perl -MLWP::Simple -e 'mirror("http://www.perl.com/", "perl.html")';
  209.  
  210. The document will not be transfered unless it has been updated.
  211.  
  212.  
  213.  
  214. =head1 LARGE DOCUMENTS
  215.  
  216. If the document you want to fetch is too large to be kept in memory,
  217. then you have two alternatives.  You can instruct the library to write
  218. the document content to a file (second $ua->request() argument is a file
  219. name):
  220.  
  221.   use LWP::UserAgent;
  222.   $ua = new LWP::UserAgent;
  223.  
  224.   my $req = new HTTP::Request 'GET',
  225.                 'http://www.sn.no/~aas/perl/www/libwww-perl-5.00.tar.gz';
  226.   $res = $ua->request($req, "libwww-perl.tar.gz");
  227.   if ($res->is_success) {
  228.      print "ok\n";
  229.   }
  230.  
  231. Or you can process the document as it arrives (second $ua->request()
  232. argument is a code reference):
  233.  
  234.   use LWP::UserAgent;
  235.   $ua = new LWP::UserAgent;
  236.   $URL = 'ftp://ftp.unit.no/pub/rfc/rfc-index.txt';
  237.  
  238.   my $expected_length;
  239.   my $bytes_received = 0;
  240.   $ua->request(HTTP::Request->new('GET', $URL),
  241.                sub {
  242.                    my($chunk, $res) = @_;
  243.                    $bytes_received += length($chunk);
  244.                unless (defined $expected_length) {
  245.                   $expected_length = $res->content_length || 0;
  246.                    }
  247.            if ($expected_length) {
  248.                 printf STDERR "%d%% - ",
  249.                               100 * $bytes_received / $expected_length;
  250.                    }
  251.                print STDERR "$bytes_received bytes received\n";
  252.  
  253.                    # XXX Should really do something with the chunk itself
  254.                # print $chunk;
  255.                });
  256.  
  257.  
  258.  
  259. =head1 HTML FORMATTING
  260.  
  261. It is easy to convert HTML code to "readable" text.
  262.  
  263.   use LWP::Simple;
  264.   use HTML::Parse;
  265.   print parse_html(get 'http://www.sn.no/libwww-perl/')->format;
  266.  
  267.  
  268.  
  269. =head1 PARSE URLS
  270.  
  271. To access individual elements of a URL, try this:
  272.  
  273.   use URI::URL;
  274.   $host = url("http://www.sn.no/")->host;
  275.  
  276. or
  277.  
  278.   use URI::URL;
  279.   $u = url("ftp://ftp.sn.no/test/aas;type=i");
  280.   print "Protocol scheme is ", $u->scheme, "\n";
  281.   print "Host is ", $u->host, " at port ", $u->port, "\n";
  282.  
  283. or even
  284.  
  285.   use URI::URL;
  286.   my($host,$port) = (url("ftp://ftp.sn.no/test/aas;type=i")->crack)[3,4];
  287.  
  288.  
  289. =head1 EXPAND RELATIVE URLS
  290.  
  291. This code reads URLs and print expanded version.
  292.  
  293.   use URI::URL;
  294.   $BASE = "http://www.sn.no/some/place?query";
  295.   while (<>) {
  296.      print url($_, $BASE)->abs->as_string, "\n";
  297.   }
  298.  
  299. We can expand URLs in an HTML document by using the parser to build a
  300. tree that we then traverse:
  301.  
  302.   %link_elements =
  303.   (
  304.    'a'    => 'href',
  305.    'img'  => 'src',
  306.    'form' => 'action',
  307.    'link' => 'href',
  308.   );
  309.  
  310.   use HTML::Parse;
  311.   use URI::URL;
  312.  
  313.   $BASE = "http://somewhere/root/";
  314.   $h = parse_htmlfile("xxx.html");
  315.   $h->traverse(\&expand_urls, 1);
  316.  
  317.   print $h->as_HTML;
  318.  
  319.   sub expand_urls
  320.   {
  321.      my($e, $start) = @_;
  322.      return 1 unless $start;
  323.      my $attr = $link_elements{$e->tag};
  324.      return 1 unless defined $attr;
  325.      my $url = $e->attr($attr);
  326.      return 1 unless defined $url;
  327.      $e->attr($attr, url($url, $BASE)->abs->as_string);
  328.   }
  329.  
  330.  
  331.  
  332. =head1 BASE URL
  333.  
  334. If you want to resolve relative links in a page you will have to
  335. determine which base URL to use.  The HTTP::Response objects now has a
  336. base() method.
  337.  
  338.   $BASE = $res->base;
  339.  
  340. =cut
  341.