java - Perl 中有类似 HttpURLConnection 的东西吗?

标签 java perl cgi cookies httpurlconnection

我想创建一个 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 模块,但找不到。 任何帮助都会有很大用处。

最佳答案

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

关于java - Perl 中有类似 HttpURLConnection 的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1105227/

相关文章:

java - 是否可以在 Gradle 中创建原型(prototype)?

perl - 如何计算 Perl 中重叠的子字符串?

regex - 重命名文件时替换和添加前导零

Android cgi web server写文件和加载perl脚本

java - DFS 方法无法正常工作

java - 解析 JSON 字符串时出现问题

java - 用户名和密码问题 : Input recognition - Java

perl - 为什么 Perl 的 sysopen 报告成功但是 $!有错误吗?

javascript - XMLHttpRequest 响应文本缺少字符

Perl - 找不到文件