【问题标题】:Convert this in Perl curl -v -H "AUTH_USER:$user" "$url" 1> "$tmpfile" 2> "$hdrfile"在 Perl 中转换 curl -v -H "AUTH_USER:$user" "$url" 1> "$tmpfile" 2> "$hdrfile"
【发布时间】:2013-12-23 07:49:30
【问题描述】:

我正在尝试将此 shell 命令转换为我正在使用的 perl 使用 WWW::Curl::Easy;

我想将详细信息写入另一个文件,并且我想将 URL 内容放入另一个文件中。到目前为止,我已经能够卷曲 URL 并向其添加标题。

现在我只想将 as shell 命令提到的 1> 输出写入文件,然后

2> 到 antohter 文件中,因为它在 shell 中

my $curl = WWW::Curl::Easy->new();
        $curl->setopt(CURLOPT_HEADER,1); 
        $curl->pushopt(WWW::Curl::Easy::CURLOPT_HTTPHEADER,['AUTH_USER:John']);
        $curl->setopt(WWW::Curl::Easy::CURLOPT_URL,"www.abc.com");
        $curl->setopt(CURLOPT_VERBOSE,1);

www.abc.com 的内容怎么放

<html>
<body>
<marquee>abc is up </marquee>
</body>
</html>

合并到一个文件中

然后这个放到另一个文件中

> GET / HTTP/1.1
Host: abc-01
Accept: */*
AUTH_USER:hojn

< HTTP/1.1 200 OK
......

【问题讨论】:

    标签: perl shell curl libcurl filehandle


    【解决方案1】:

    粗略阅读documentation 和libcurl docs 表明您可能需要:

        # A filehandle, reference to a scalar or reference to a typeglob can be used here.
        my $response_body;
        $curl->setopt(CURLOPT_WRITEDATA,\$response_body);
    
        my $response_header;
        $curl->setopt(CURLOPT_WRITEHEADER,\$response_header);
    

    【讨论】:

    • 那么我们在哪里定义文件句柄? ,假设我们必须写入 /usr/bin/header.txt /usr/bin/content.txt 中的文件,你在哪里定义?
    • 您定义并写入它,就像您对任何文件一样。
    • response_body 也包含响应标头,我只想将 html 代码放入一个文件中,而在另一个文件中详细说明,但她的响应正文包含正在获取的完整响应,我只想写我正在卷曲到文件中的 URL 的 html 代码
    【解决方案2】:

    使用 libcurl 时,将其 documentation 放在手边会很有用。

    浏览选项,我们找到CURLOPT_HEADERFUNCTION & WRITEHEADER 和CURLOPT_WRITEFUNCTION & WRITEDATA。

    use strict;
    use warnings;
    
    use Net::Curl::Easy qw( /^CURLOPT_/ );
    
    my $url = 'http://stackoverflow.com/';
    
    my $easy = Net::Curl::Easy->new();
    
    open(my $fh_header, '>:raw', 'header.out') or die $!;
    open(my $fh_data,   '>:raw', 'data.out'  ) or die $!;
    
    $easy->setopt(CURLOPT_URL,         $url);
    $easy->setopt(CURLOPT_WRITEHEADER, $fh_header);
    $easy->setopt(CURLOPT_WRITEDATA,   $fh_data);
    $easy->perform();
    

    注意:我使用 Net::Curl 而不是 WWW::Curl 因为我知道并信任它。只要它为CURLOPT_WRITEFUNCTION 和CURLOPT_HEADERFUNCTION 提供可感知Perl 的默认值,上述内容也应该适用于WWW::Curl。如果没有,您还需要为这些选项提供值。

    【讨论】:

    • 在 data.out 文件中,由于某种原因,标题也被写入了我只想在 data.out 中编写 html 代码。任何方式都可以做到这一点
    • header.out 非常完美,但 data.out 也包含 header.out 中的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多