home *** CD-ROM | disk | FTP | other *** search
/ CD Actual Thematic 7: Programming / CDAT7.iso / Share / Editores / Perl5 / perl / lib / site / HTTP / Request / Common.pm
Encoding:
Perl POD Document  |  1997-08-10  |  8.4 KB  |  322 lines

  1. # $Id: Common.pm,v 1.3 1997/08/04 15:38:58 aas Exp $
  2. #
  3. package HTTP::Request::Common;
  4.  
  5. use strict;
  6. use vars qw(@ISA @EXPORT @EXPORT_OK $VERSION);
  7.  
  8. require Exporter;
  9. @ISA=qw(Exporter);
  10.  
  11. @EXPORT=qw(GET HEAD PUT POST);
  12. @EXPORT_OK=qw(cat);
  13.  
  14. require HTTP::Request;
  15. use Carp();
  16.  
  17. $VERSION = sprintf("%d.%02d", q$Revision: 1.3 $ =~ /(\d+)\.(\d+)/);
  18.  
  19. my $CRLF = "\015\012";   # "\r\n" is not portable
  20.  
  21. sub GET  { _simple_req('GET',  @_); }
  22. sub HEAD { _simple_req('HEAD', @_); }
  23. sub PUT  { _simple_req('PUT' , @_); }
  24.  
  25. sub POST
  26. {
  27.     my $url = shift;
  28.     my $req = HTTP::Request->new(POST => $url);
  29.     my $content;
  30.     $content = shift if @_ and ref $_[0];
  31.     my($k, $v);
  32.     while (($k,$v) = splice(@_, 0, 2)) {
  33.     if (lc($k) eq 'content') {
  34.         $content = $v;
  35.     } else {
  36.         $req->push_header($k, $v);
  37.     }
  38.     }
  39.     my $ct = $req->header('Content-Type');
  40.     unless ($ct) {
  41.     $ct = 'application/x-www-form-urlencoded';
  42.     } elsif ($ct eq 'form-data') {
  43.     $ct = 'multipart/form-data';
  44.     }
  45.  
  46.     if (ref $content) {
  47.     if (lc($ct) eq 'multipart/form-data') {    #XXX: boundary="..."
  48.         my $boundary;
  49.         ($content, $boundary) = form_data($content, $boundary);
  50.         $ct = qq(multipart/form-data; boundary="$boundary");
  51.     } else {
  52.         # We use a temporary URI::URL object to format
  53.         # the application/x-www-form-urlencoded content.
  54.         require URI::URL;
  55.         my $url = URI::URL->new('http:');
  56.         $url->query_form(@$content);
  57.         $content = $url->equery;
  58.     }
  59.     }
  60.  
  61.     $req->header('Content-Type' => $ct);  # might be redundant
  62.     if (defined($content)) {
  63.     $req->header('Content-Length' => length($content));
  64.     $req->content($content);
  65.     }
  66.     $req;
  67. }
  68.  
  69.  
  70. sub _simple_req
  71. {
  72.     my($method, $url) = splice(@_, 0, 2);
  73.     my $req = HTTP::Request->new($method => $url);
  74.     my($k, $v);
  75.     while (($k,$v) = splice(@_, 0, 2)) {
  76.     if (lc($k) eq 'content') {
  77.         $req->add_content($v);
  78.     } else {
  79.         $req->push_header($k, $v);
  80.     }
  81.     }
  82.     $req;
  83. }
  84.  
  85.  
  86. sub form_data   # RFC1867
  87. {
  88.     my($data, $boundary) = @_;
  89.     my @parts;
  90.     my($k,$v);
  91.     while (($k,$v) = splice(@$data, 0, 2)) {
  92.     if (ref $v) {
  93.         my $file = shift(@$v);
  94.         my $usename = shift(@$v);
  95.         unless (defined $usename) {
  96.         $usename = $file;
  97.         $usename =~ s,.*/,, if defined($usename);
  98.         }
  99.         my $disp = qq(form-data; name="$k");
  100.         $disp .= qq(; filename="$usename") if $usename;
  101.         my $content = "";
  102.         my $h = HTTP::Headers->new(@$v);
  103.         my $ct = $h->header("Content-Type");
  104.         if ($file) {
  105.         local(*F);
  106.         local($/) = undef; # slurp files
  107.         open(F, $file) or Carp::croak("Can't open file $file: $!");
  108.         $content = <F>;
  109.         close(F);
  110.         unless ($ct) {
  111.             require LWP::MediaTypes;
  112.             $ct = LWP::MediaTypes::guess_media_type($file);
  113.             $h->header("Content-Type" => $ct); # XXX: content-encoding
  114.         }
  115.         }
  116.         if ($h->header("Content-Disposition")) {
  117.         $h->remove_header("Content-Disposition");
  118.         $disp = $h->remove_header("Content-Disposition");
  119.         }
  120.         if ($h->header("Content")) {
  121.         $content = $h->header("Content");
  122.         $h->remove_header("Content");
  123.         }
  124.         push(@parts, "Content-Disposition: $disp$CRLF" .
  125.                          $h->as_string($CRLF) .
  126.                          "$CRLF$content");
  127.     } else {
  128.         push(@parts, qq(Content-Disposition: form-data; name="$k"$CRLF$CRLF$v));
  129.     }
  130.     }
  131.     return "" unless @parts;
  132.     $boundary = boundary() unless $boundary;
  133.  
  134.     my $bno = 1;
  135.   CHECK_BOUNDARY:
  136.     {
  137.     for (@parts) {
  138.         if (index($_, $boundary) >= 0) {
  139.         # must have a better boundary
  140.         #warn "Need something better that '$boundary' as boundary\n";
  141.         $boundary = boundary(++$bno);
  142.         redo CHECK_BOUNDARY;
  143.         }
  144.     }
  145.     last;
  146.     }
  147.  
  148.     my $content = "--$boundary$CRLF" .
  149.                   join("$CRLF--$boundary$CRLF", @parts) .
  150.                   "$CRLF--$boundary--$CRLF";
  151.     wantarray ? ($content, $boundary) : $content;
  152. }
  153.  
  154.  
  155. sub boundary
  156. {
  157.     my $size = shift || 1;
  158.     require MIME::Base64;
  159.     MIME::Base64::encode(join("", map chr(rand(256)), 1..$size*3), "");
  160. }
  161.  
  162. 1;
  163.  
  164. __END__
  165.  
  166. =head1 NAME
  167.  
  168. HTTP::Request::Common - Construct common HTTP::Request objects
  169.  
  170. =head1 SYNOPSIS
  171.  
  172.   use HTTP::Request::Common;
  173.   $ua = LWP::UserAgent->new;
  174.   $ua->request(GET 'http://www.sn.no/');
  175.   $ua->request(POST 'http://somewhere/foo', [foo => bar, bar => foo]);
  176.  
  177. =head1 DESCRIPTION
  178.  
  179. This module provide functions that return newly created HTTP::Request
  180. objects.  These functions are usually more convenient than the
  181. standard HTTP::Request constructor for these common requests.  The
  182. following functions are provided.
  183.  
  184. =over 4
  185.  
  186. =item GET $url, [Header => Value,...]
  187.  
  188. The GET() function returns a HTTP::Request object initialized with the
  189. GET method and the specified URL.  Without additional arguments it
  190. is exactly equivalent to the following call
  191.  
  192.   HTTP::Request->new(GET => $url)
  193.  
  194. but is less clutter.  It also reads better when used together with the
  195. LWP::UserAgent->request() method:
  196.  
  197.   my $ua = new LWP::UserAgent;
  198.   my $res = $ua->request(GET 'http://www.sn.no')
  199.   if ($res->is_success) { ...
  200.  
  201. You can also initialize the header values in the request by specifying
  202. some key/value pairs as optional arguments.  For instance:
  203.  
  204.   $ua->request(GET 'http://www.sn.no',
  205.                If_Match => 'foo',
  206.                    From     => 'gisle@aas.no',
  207.               );
  208.  
  209. A header key called 'Content' is special and when seen the value will
  210. initialize the content part of the request instead of setting a header.
  211.  
  212. =item HEAD $url, [Header => Value,...]
  213.  
  214. Like GET() but the method in the request is HEAD.
  215.  
  216. =item PUT $url, [Header => Value,...]
  217.  
  218. Like GET() but the method in the request is PUT.
  219.  
  220. =item POST $url, [$form_ref], [Header => Value,...]
  221.  
  222. This works mostly like GET() with POST as method, but this function
  223. also takes a second optional array reference parameter ($form_ref).
  224. This argument can be used to pass key/value pairs for the form
  225. content.  By default we will initialize a request using the
  226. C<application/x-www-form-urlencoded> content type.  This means that
  227. you can emulate a HTML E<lt>form> POSTing like this:
  228.  
  229.   POST 'http://www.perl.org/survey.cgi',
  230.        [ name  => 'Gisle',
  231.          email => 'gisle@aas.no',
  232.          gender => 'm',
  233.          born   => '1964',
  234.          trust  => '3%',
  235.     ];
  236.  
  237. This will create a HTTP::Request object that looks like this:
  238.  
  239.   POST http://www.perl.org/survey.cgi
  240.   Content-Length: 61
  241.   Content-Type: application/x-www-form-urlencoded
  242.  
  243.   name=Gisle&email=gisle%40aas.no&gender=m&born=1964&trust=3%25
  244.  
  245. The POST method also supports the C<multipart/form-data> content used
  246. for I<Form-based File Upload> as specified in RFC 1867.  You trigger
  247. this content format by specifying a content type of C<'form-data'>.
  248. If one of the values in the $form_ref is an array reference, then it
  249. is treated as a file part specification with the following values:
  250.  
  251.   [ $file, $filename, Header => Value... ]
  252.  
  253. The first value in the array ($file) is the name of a file to open.
  254. This file will be read an its content placed in the request.  The
  255. routine will croak if the file can't be opened.  Use an undef as $file
  256. value if you want to specify the content directly.  The $filename is
  257. the filename to report in the request.  If this value is undefined,
  258. then the basename of the $file will be used.  You can specify an empty
  259. string as $filename if you don't want any filename in the request.
  260.  
  261. Sending my F<~/.profile> to the survey used as example above can be
  262. achieved by this:
  263.  
  264.   POST 'http://www.perl.org/survey.cgi',
  265.        Content_Type => 'form-data',
  266.        Content      => [ name  => 'Gisle Aas',
  267.                          email => 'gisle@aas.no',
  268.                          gender => 'm',
  269.                          born   => '1964',
  270.                          init   => ["$ENV{HOME}/.profile"],
  271.                        ]
  272.  
  273. This will create a HTTP::Request object that almost looks this (the
  274. boundary and the content of your F<~/.profile> is likely to be
  275. different):
  276.  
  277.   POST http://www.perl.org/survey.cgi
  278.   Content-Length: 388
  279.   Content-Type: multipart/form-data; boundary="6G+f"
  280.  
  281.   --6G+f
  282.   Content-Disposition: form-data; name="name"
  283.   
  284.   Gisle Aas
  285.   --6G+f
  286.   Content-Disposition: form-data; name="email"
  287.   
  288.   gisle@aas.no
  289.   --6G+f
  290.   Content-Disposition: form-data; name="gender"
  291.   
  292.   m
  293.   --6G+f
  294.   Content-Disposition: form-data; name="born"
  295.   
  296.   1964
  297.   --6G+f
  298.   Content-Disposition: form-data; name="init"; filename=".profile"
  299.   Content-Type: text/plain
  300.   
  301.   PATH=/local/perl/bin:$PATH
  302.   export PATH
  303.  
  304.   --6G+f--
  305.  
  306. =back
  307.  
  308. =head1 SEE ALSO
  309.  
  310. L<HTTP::Request>, L<LWP::UserAgent>
  311.  
  312.  
  313. =head1 COPYRIGHT
  314.  
  315. Copyright 1997, Gisle Aas
  316.  
  317. This library is free software; you can redistribute it and/or
  318. modify it under the same terms as Perl itself.
  319.  
  320. =cut
  321.  
  322.