⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lite.pm

📁 lrc 歌词解析和实时显示源码, 是开发 mp3, 播放器的很好的模块
💻 PM
📖 第 1 页 / 共 2 页
字号:
sub headers_array{  my $self = shift;    my @array = ();    foreach my $header (keys %{$self->{'resp-headers'}})  {    my $aref = ${$self->{'resp-headers'}}{$header};    foreach my $value (@$aref)    {      push @array, "$header: $value";    }  }  return @array;}sub headers_string{  my $self = shift;    my $string = "";    foreach my $header (keys %{$self->{'resp-headers'}})  {    my $aref = ${$self->{'resp-headers'}}{$header};    foreach my $value (@$aref)    {      $string .= "$header: $value\n";    }  }  return $string;}sub get_header{  my $self = shift;  my $header = shift;  return $self->{'resp-headers'}{$header};}sub http11_mode{  my $self = shift;  my $mode = shift;  $self->{HTTP11} = $mode;}sub prepare_post{  my $self = shift;  my $varref = shift;    my $body = "";  while (my ($var,$value) = map { escape($_) } each %$varref)  {    if ($body)    {      $body .= "&$var=$value";    } else {      $body = "$var=$value";    }  }  $self->{content} = $body;  $self->{headers}{'Content-Type'} = "application/x-www-form-urlencoded"    unless defined ($self->{headers}{'Content-Type'}) and     $self->{headers}{'Content-Type'};  $self->{method} = "POST";}sub http_write{  my $self = shift;  my ($fh,$line) = @_;  if ($self->{holdback}) {     $self->{HTTPWriteBuffer} .= $line;     return;  } else {     if (defined $self->{HTTPWriteBuffer}) {   # copy previously buffered, if any         $line = $self->{HTTPWriteBuffer} . $line;     }  }  my $size = length($line);  my $bytes = syswrite($fh, $line, length($line) , 0 );  # please double check new length limit                                                         # is this ok?  while ( ($size - $bytes) > 0) {    $bytes += syswrite($fh, $line, length($line)-$bytes, $bytes );  # also here  }} sub http_read{  my $self = shift;  my ($fh,$headmode,$chunkmode,$chunksize) = @_;  $self->{DEBUG} && $self->DEBUG("read handle=$fh, headm=$headmode, chunkm=$chunkmode, chunksize=$chunksize");  my $res;  if (($headmode == 0 && $chunkmode eq "0") || ($chunkmode eq "chunk")) {    my $bytes_to_read = $chunkmode eq "chunk" ?        ($chunksize < $BLOCKSIZE ? $chunksize : $BLOCKSIZE) :        $BLOCKSIZE;    $res = $self->http_readbytes($fh,$self->{timeout},$bytes_to_read);  } else {     $res = $self->http_readline($fh,$self->{timeout});    }  if ($res) {    if ($self->{DEBUG}) {      $self->DEBUG("read got ".length($$res)." bytes");      my $str = $$res;      $str =~ s{([\x00-\x1F\x7F-\xFF])}{.}g;      $self->DEBUG("read: ".$str);    }  }  return $res;}sub http_readline{  my $self = shift;  my ($fh, $timeout) = @_;  my $EOL = "\n";  $self->{DEBUG} && $self->DEBUG("readline handle=$fh, timeout=$timeout");    # is there a line in the buffer yet?  while ($self->{HTTPReadBuffer} !~ /$EOL/)  {    # nope -- wait for incoming data    my ($inbuf,$bits,$chars) = ("","",0);    vec($bits,fileno($fh),1)=1;    my $nfound = select($bits, undef, $bits, $timeout);    if ($nfound == 0)    {      # Timed out      return undef;    } else {      # Get the data      $chars = sysread($fh, $inbuf, $BLOCKSIZE);      $self->{DEBUG} && $self->DEBUG("sysread $chars bytes");    }    # End of stream?    if ($chars <= 0 && !$!{EAGAIN})    {      last;    }    # tag data onto end of buffer    $self->{HTTPReadBuffer}.=$inbuf;  }  # get a single line from the buffer  my $nlat = index($self->{HTTPReadBuffer}, $EOL);  my $newline;  my $oldline;  if ($nlat > -1)  {    $newline = substr($self->{HTTPReadBuffer},0,$nlat+1);    $oldline = substr($self->{HTTPReadBuffer},$nlat+1);  } else {    $newline = substr($self->{HTTPReadBuffer},0);    $oldline = "";  }  # and update the buffer  $self->{HTTPReadBuffer}=$oldline;  return length($newline) ? \$newline : 0;}sub http_readbytes{  my $self = shift;  my ($fh, $timeout, $bytes) = @_;  my $EOL = "\n";  $self->{DEBUG} && $self->DEBUG("readbytes handle=$fh, timeout=$timeout, bytes=$bytes");    # is there enough data in the buffer yet?  while (length($self->{HTTPReadBuffer}) < $bytes)  {    # nope -- wait for incoming data    my ($inbuf,$bits,$chars) = ("","",0);    vec($bits,fileno($fh),1)=1;    my $nfound = select($bits, undef, $bits, $timeout);    if ($nfound == 0)    {      # Timed out      return undef;    } else {      # Get the data      $chars = sysread($fh, $inbuf, $BLOCKSIZE);      $self->{DEBUG} && $self->DEBUG("sysread $chars bytes");    }    # End of stream?    if ($chars <= 0 && !$!{EAGAIN})    {      last;    }    # tag data onto end of buffer    $self->{HTTPReadBuffer}.=$inbuf;  }  my $newline;  my $buflen;  if (($buflen=length($self->{HTTPReadBuffer})) >= $bytes)  {    $newline = substr($self->{HTTPReadBuffer},0,$bytes+1);    if ($bytes+1 < $buflen) {      $self->{HTTPReadBuffer} = substr($self->{HTTPReadBuffer},$bytes+1);    } else {      $self->{HTTPReadBuffer} = "";    }  } else {    $newline = substr($self->{HTTPReadBuffer},0);    $self->{HTTPReadBuffer} = "";  }  return length($newline) ? \$newline : 0;}sub upper{  my ($str) = @_;  if (defined($str)) {    return uc($str);  } else {    return undef;  }}1;__END__=pod=head1 NAMEHTTP::Lite - Lightweight HTTP implementation=head1 SYNOPSIS    use HTTP::Lite;    $http = new HTTP::Lite;    $req = $http->request("http://www.cpan.org/")         or die "Unable to get document: $!";    print $http->body();=head1 DESCRIPTION    HTTP::Lite is a stand-alone lightweight HTTP/1.1 implementation    for perl.  It is not intended as a replacement for the    fully-features LWP module.  Instead, it is intended for use in    situations where it is desirable to install the minimal number of    modules to achieve HTTP support, or where LWP is not a good    candidate due to CPU overhead, such as slower processors.    HTTP::Lite is also significantly faster than LWP.    HTTP::Lite is ideal for CGI (or mod_perl) programs or for bundling    for redistribution with larger packages where only HTTP GET and    POST functionality are necessary.    HTTP::Lite supports basic POST and GET operations only.  As of    0.2.1, HTTP::Lite supports HTTP/1.1 and is compliant with the Host    header, necessary for name based virtual hosting.  Additionally,    HTTP::Lite now supports Proxies.    As of 2.0.0 HTTP::Lite now supports a callback to allow processing    of request data as it arrives.  This is useful for handling very    large files without consuming memory.    If you require more functionality, such as FTP or HTTPS, please    see libwwwperl (LWP).  LWP is a significantly better and more    comprehensive package than HTTP::Lite, and should be used instead    of HTTP::Lite whenever possible.=head1 CONSTRUCTOR=over 4=item newThis is the constructor for HTTP::Lite.  It presently takes noarguments.  A future version of HTTP::Lite might accept parameters.=back=head1 METHODS=over 4=item request ( $url, $data_callback, $cbargs )Initiates a request to the specified URL.Returns undef if an I/O error is encountered, otherwise the HTTPstatus code will be returned.  200 series status codes representsuccess, 300 represent temporary errors, 400 represent permanenterrors, and 500 represent server errors.See F<http://www.w3.org/Protocols/HTTP/HTRESP.html> for detailledinformation about HTTP status codes.The $data_callback parameter, if used, is a way to filter the data as it isreceived or to handle large transfers.  It must be a function reference, andwill be passed: a reference to the instance of the http request making thecallback, a reference to the current block of data about to be added to thebody, and the $cbargs parameter (which may be anything).  It must returneither a reference to the data to add to the body of the document, or undef.If set_callback is used, $data_callback and $cbargs are not used.  $cbargsmay be either a scalar or a reference.The data_callback is called as:   &$data_callback( $self, $dataref, $cbargs )An example use to save a document to file is:  # Write the data to the filehandle $cbargs  sub savetofile {    my ($self,$phase,$dataref,$cbargs) = @_;    print $cbargs $$dataref;    return undef;  }  $url = "$testpath/bigbinary.dat";  open OUT, ">bigbinary.dat";  $res = $http->request($url, \&savetofile, OUT);  close OUT;=item set_callback ( $functionref, $dataref )At various stages of the request, callbacks may be used to modify thebehaviour or to monitor the status of the request.  These work like the$data_callback parameter to request(), but are more verstaile.  Usingset_callback disables $data_callback in request()The callbacks are called as:   callback ( $self, $phase, $dataref, $cbargs )The current phases are:  connect - connection has been established and headers are being            transmitted.              content-length - return value is used as the content-length.  If undef,            and prepare_post() was used, the content length is            calculated.                     done-headers - all headers have been sent    content - return value is used as content and is sent to client.  Return            undef to use the internal content defined by prepare_post().              content-done - content has been successfuly transmitted.    data - A block of data has been received.  The data is referenced by            $dataref.  The return value is dereferenced and replaces the            content passed in.  Return undef to avoid using memory for large            documents.  done - Request is done.=item prepare_post ( $hashref )Takes a reference to a hashed array of post form variables to upload. Create the HTTP body and sets the method to POST.=item http11_mode ( 0 | 1 )Turns on or off HTTP/1.1 support.  This is off by default due tobroken HTTP/1.1 servers.  Use 1 to enable HTTP/1.1 support.=item add_req_header ( $header, $value )=item get_req_header ( $header )=item delete_req_header ( $header )Add, Delete, or a HTTP header(s) for the request.  These functionsallow you to override any header.  Presently, Host, User-Agent,Content-Type, Accept, and Connection are pre-defined by the HTTP::Litemodule.  You may not override Host, Connection, or Accept.To provide (proxy) authentication or authorization, you would use:    use HTTP::Lite;    use MIME::Base64;    $http = new HTTP::Lite;    $encoded = encode_base64('username:password');    $http->add_req_header("Authorization", $encoded);B<NOTE>: The present implementation limits you to one instanceof each header.=item bodyReturns the body of the document retured by the remote server.=item headers_arrayReturns an array of the HTTP headers returned by the remoteserver.=item headers_stringReturns a string representation of the HTTP headers returned bythe remote server.=item get_header ( $header )Returns an array of values for the requested header.  B<NOTE>: HTTP requests are not limited to a single instance ofeach header.  As a result, there may be more than one entry forevery header.=item protocolReturns the HTTP protocol identifier, as reported by the remoteserver.  This will generally be either HTTP/1.0 or HTTP/1.1.=item proxy ( $proxy_server )The URL or hostname of the proxy to use for the next request.=item statusReturns the HTTP status code returned by the server.  This isalso reported as the return value of I<request()>.=item status_messageReturns the textual description of the status code as returnedby the server.  The status string is not required to adhere toany particular format, although most HTTP servers use a standardset of descriptions.=item resetYou must call this prior to re-using an HTTP::Lite handle,otherwise the results are undefined.=item local_addr ( $ip )Explicity select the local IP address.  0.0.0.0 (default) lets the systemchoose.=item local_port ( $port )Explicity select the local port.  0 (default and reccomended) lets thesystem choose.=item method ( $method )Explicity set the method.  Using prepare_post or reset overrides thissetting.  Usual choices are GET, POST, PUT, HEAD=head1 EXAMPLES    # Get and print out the headers and body of the CPAN homepage    use HTTP::Lite;    $http = new HTTP::Lite;    $req = $http->request("http://www.cpan.org/")        or die "Unable to get document: $!";    die "Request failed ($req): ".$http->status_message()      if $req ne "200";    @headers = $http->headers_array();    $body = $http->body();    foreach $header (@headers)    {      print "$header$CRLF";    }    print "$CRLF";    print "$body$CRLF";    # POST a query to the dejanews USENET search engine    use HTTP::Lite;    $http = new HTTP::Lite;    %vars = (             "QRY" => "perl",             "ST" => "MS",             "svcclass" => "dncurrent",             "DBS" => "2"            );    $http->prepare_post(\%vars);    $req = $http->request("http://www.deja.com/dnquery.xp")      or die "Unable to get document: $!";    print "req: $req\n";    print $http->body();=head1 UNIMPLEMENTED    - FTP     - HTTPS (SSL)    - Authenitcation/Authorizaton/Proxy-Authorization      are not directly supported, and require MIME::Base64.    - Redirects (Location) are not automatically followed    - multipart/form-data POSTs are not directly supported (necessary      for File uploads).    =head1 BUGS    Some broken HTTP/1.1 servers send incorrect chunk sizes    when transferring files.  HTTP/1.1 mode is now disabled by    default.=head1 AUTHORRoy Hooper <rhooper@thetoybox.org>=head1 SEE ALSOL<LWP>RFC 2068 - HTTP/1.1 -http://www.w3.org/=head1 COPYRIGHTCopyright (c) 2000-2002 Roy Hooper.  All rights reserved.This program is free software; you can redistribute it and/or modify itunder the same terms as Perl itself.=cut

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -