Perl中是否有类似于HttpURLConnection的东西?

3

我希望创建一个HTTPURLConnection到一个PHP脚本,并获取脚本返回的HTTP响应。在Perl中有没有一种方法可以实现这个功能?

简而言之,我想要Perl的等价物来实现以下功能:

            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) + "'");
            // }

我正在尝试搜索类似的Perl模块,但是没有找到任何一个。 任何帮助都将非常有用。


在上面的例子中,'cookie' 是一个字符串。 - Sam
2个回答

6

尝试使用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";
 }

在你的例子中,为什么要这样做: $ua->cookie_jar({ file => "$ENV{HOME}/.cookies.txt" });您能否详细解释一下? - Sam
2
@Sam,我认为你想要使用$ua->cookie_jar({ });创建一个内存中的Cookie Jar,然后在其上调用$ua->cookie_jar->set_cookie(); - Sinan Ünür

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接