Perl – Using HTTP::Lite

I recently had to use the HTTP::Lite perl module and thought I would share an example of how to use it. HTTP::Lite was is available on www.cpan.org; its very lightweight and has no dependancies other than Socket & Fcntl which included with almost all Perl implementations by default.

Based on the examples by the HTTP::Lite author Roy Hooper <rhooper@thetoybox.org>

PERL:
  1. #!perl
  2.  
  3. use HTTP::Lite;
  4.  
  5.  
  6. #
  7. # Get and print out the headers and body of the Google homepage
  8. #
  9.  
  10. $http = new HTTP::Lite;
  11.  
  12. $req = $http->request("http://www.google.co.uk/")
  13.    or die "Unable to get document: $!";
  14.  
  15. # Print the reconstructed status line
  16. print $http->protocol() . " " . $req . " " . $http->status_message() . "";
  17.  
  18. # Get the Headers & Body
  19. @headers = $http->headers_array();
  20. $body    = $http->body();
  21.  
  22. # Display each Header
  23. foreach $header (@headers) {
  24.   print $header . "\n";
  25. }
  26. print "\n\n";
  27.  
  28. # Display the Body
  29. print $body . "\n";
  30.  
  31.  
  32.  
  33. #
  34. # Execute a Google Search using the POST method
  35. #
  36.  
  37. $http = new HTTP::Lite;
  38.  
  39. # Post variables
  40. %vars = (
  41.          "hl" => "en",
  42.          "q" => "cpan",
  43.          "btnG" => "Search",
  44.          "meta" => ""
  45.         );
  46. $http->prepare_post(\%vars);
  47.  
  48. $req = $http->request("http://www.google.co.uk/search")
  49.   or die "Unable to get document: $!";
  50.  
  51. # Print the reconstructed status line
  52. print $http->protocol() . " " . $req . " " . $http->status_message() . "";
  53.  
  54. # Get the Headers & Body
  55. @headers = $http->headers_array();
  56. $body    = $http->body();
  57.  
  58. # Display each Header
  59. foreach $header (@headers) {
  60.   print $header . "\n";
  61. }
  62. print "\n\n";
  63.  
  64. # Display the Body
  65. print $body . "\n";

Google doesnt support queries by POST methods anymore, so the response to the second request here will be a "501 Not Implemented".