views:

195

answers:

2

I want to create an HTTPURLConnection to a PHP script and get the HTTP response returned by the script. Is there a way to do this in Perl?

In short i want Perl equivalent to following:

            java.net.URL url = new java.net.URL(urlPath);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Content-Length", Integer.toString(body.length())); 

            conn.setRequestProperty("Cookie", "ONTCred=" + cookie);

            conn.connect();

            java.io.PrintWriter pw = new java.io.PrintWriter(conn.getOutputStream());
            pw.print(body); // "send" the body
            pw.flush();
            pw.close();

            if (conn.getResponseCode() != java.net.HttpURLConnection.HTTP_OK) {
                    throw new java.io.IOException("Error on POST to " + url + ": " + conn.getResponseMessage());
            }

            // for debugging, if you want to see the header info, uncomment this section
            // for (String key : conn.getHeaderFields().keySet()) {
            //      System.out.println("header: '" + key + "' = '" + conn.getHeaderField(key) + "'");
            // }

I am trying to search similar perl module, but could not find any. Any help would be of great use.

+5  A: 

Try LWP:

 # Create a user agent object
 use LWP::UserAgent;
 my $ua = LWP::UserAgent->new;

 # Create a request
 my $req = HTTP::Request->new(POST => $url);
 $req->content_type('application/x-www-form-urlencoded');

 # cookies 
 $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });

 # Pass request to the user agent and get a response back
 my $res = $ua->request($req);

 # Check the outcome of the response
 if ($res->is_success) {
    print $res->content;
 } else {
    print $res->status_line, "\n";
 }
dfa
In you example why are you doing this: $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });Can you please explain little bit in more detail?
@Sam see http://search.cpan.org/perldoc?HTTP::Cookies
Sinan Ünür
@Sam, I think you want to create an in memory cookie jar using `$ua->cookie_jar({ });` and then call `$ua->cookie_jar->set_cookie();` on it.
Sinan Ünür
A: 

Depending on what your goals are, WWW::Mechanize might be a better fit.