【问题标题】:Extract HTTP body from curl response从 curl 响应中提取 HTTP 正文
【发布时间】:2022-01-04 21:36:32
【问题描述】:

我使用包 WWW::Curl::Easy 进行 API 调用,这是我的示例代码:

use WWW::Curl::Easy;

my $curl = WWW::Curl::Easy->new();

$curl->setopt(CURLOPT_POST, 1);
$curl->setopt(CURLOPT_HEADER, 1);
$curl->setopt(CURLOPT_HTTPHEADER, ['Accept: text/xml; charset=utf-8', 'Content-Type:text/xml; charset=utf-8', 'SOAPAction: "importSheet"']);
$curl->setopt(CURLOPT_POSTFIELDS, $requestMessage);
$curl->setopt(CURLOPT_URL, $tom::{'setup'}{'api'}{'carrier'}{'url'});


my $response;
$curl->setopt(CURLOPT_WRITEDATA, \$response);

main::_log(Dumper(\$curl));

my $ret = $curl->perform();

如您所见,我将响应保存到变量 $response 中,但我想知道仅提取该响应的 HTTP 正文的最佳方法是什么,而不需要标头和其他内容。

现在我的回复是这样的:

HTTP/1.1 500 Internal Server Error
Date: Fri, 26 Nov 2021 21:38:42 GMT
Content-Type: text/xml
Connection: keep-alive
Content-Length: 241
Set-Cookie: TS01972c9d=01a27f45ea407d6a9622e8d70528d3201676317364865a22da7d73be308d9e49021a872fbfe71877fbee80ce454071bc9a105a4e33; Path=/; Domain=.test.test.com

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring>user_not_found</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>

但我想只获得没有标题的响应正文,所以它应该是这样的:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Server</faultcode><faultstring>user_not_found</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>

我尝试过类似的东西:

$response_content = HTTP::Response->parse("$response") ;
$response_content = $response_content->content;

但它仍然包含标题。

【问题讨论】:

    标签: perl http curl response


    【解决方案1】:

    仅提取该响应的 HTTP 正文的最佳方法是什么

    直接删除

    $curl->setopt(CURLOPT_HEADER, 1);
    

    或者改成

    $curl->setopt(CURLOPT_HEADER, 0);
    

    如果您还想要标题,则还添加以下内容:

    $self->setopt(CURLOPT_HEADERDATA, \$head);
    

    大家一起:

    my $curl = WWW::Curl::Easy->new();
    
    $curl->setopt(CURLOPT_POST,       1);
    $curl->setopt(CURLOPT_URL,        ...);
    $curl->setopt(CURLOPT_HTTPHEADER, ...);
    $curl->setopt(CURLOPT_POSTFIELDS, ...);
    
    # $curl->setopt(CURLOPT_HEADER, 0);  This is the default.
    $curl->setopt(CURLOPT_WRITEDATA,  \my $body);   # If you want the body.
    $curl->setopt(CURLOPT_HEADERDATA, \my $head);   # If you want the head.
    

    【讨论】:

      【解决方案2】:

      您可以使用$curl-&gt;setopt(CURLOPT_HEADERDATA, \$head)$curl-&gt;setopt(CURLOPT_FILE, \$body) 为响应中的标头和正文数据设置单独的目标。

      【讨论】:

      • CURLOPT_FILECURLOPT_WRITEDATA 的旧名称
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-20
      • 1970-01-01
      相关资源
      最近更新 更多