【问题标题】:Is there any thing similar to HttpURLConnection in Perl?Perl 中有没有类似 HttpURLConnection 的东西?
【发布时间】:2010-11-09 11:11:06
【问题描述】:

我想创建一个到 PHP 脚本的 HTTPURLConnection 并获取脚本返回的 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'是一个字符串

标签: java perl cgi cookies httpurlconnection


【解决方案1】:

试试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,我想你想使用$ua->cookie_jar({ }); 创建一个内存cookie jar,然后调用$ua->cookie_jar->set_cookie();
【解决方案2】:

根据您的目标,WWW::Mechanize 可能更合适。

【讨论】:

    猜你喜欢
    • 2010-10-08
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多