【问题标题】:How to get a portion of the response by curl?如何通过 curl 获得部分响应?
【发布时间】:2019-05-18 12:56:20
【问题描述】:

通过 curl 获取 url 会导致无限响应。当我在浏览器中打开网址时,将开始无限下载文件。该 url 属于一个摄像头,它通知摄像头上发生的事件,如运动检测等。但它不是一个请求/一个响应的形式。它采用单一请求/无限响应的形式。为此,我需要削减输出以获得“--boundary”之间的一段。 除了描述之外,我还举了一个例子:

--boundary
Content-Type: application/xml; charset="UTF-8"
Content-Length: 480

<EventNotificationAlert version="2.0" xmlns="http://www.std-cgi.com/ver20/XMLSchema">
<ipAddress>192.168.14.227</ipAddress>
<portNo>80</portNo>
<protocol>HTTP</protocol>
<macAddress>b8:41:5f:02:81:45</macAddress>
<channelID>1</channelID>
<dateTime>2019-05-18T17:15:02+03:30</dateTime>
<activePostCount>0</activePostCount>
<eventType>videoloss</eventType>
<eventState>inactive</eventState>
<eventDescription>videoloss alarm</eventDescription>
</EventNotificationAlert>
--boundary
Content-Type: application/xml; charset="UTF-8"
Content-Length: 480

<EventNotificationAlert version="2.0" xmlns="http://www.std-cgi.com/ver20/XMLSchema">
<ipAddress>192.168.14.227</ipAddress>
<portNo>80</portNo>
<protocol>HTTP</protocol>
<macAddress>b8:41:5f:02:81:45</macAddress>
<channelID>1</channelID>
<dateTime>2019-05-18T17:15:02+03:30</dateTime>
<activePostCount>0</activePostCount>
<eventType>videoloss</eventType>
<eventState>inactive</eventState>
<eventDescription>videoloss alarm</eventDescription>
</EventNotificationAlert>
--boundary

介绍完之后,我的问题是: 如何使用 curl 仅获取第一个边界并且不要等到响应结束,因为它永远不会结束?每当我看到第一个“--boundary”时,我都需要切割。 另一个替代切割的解决方案是定义一个回调函数来获取 url 作为响应发送的所有内容并处理它并保留信息。 如何做到这两点?

【问题讨论】:

    标签: curl libcurl


    【解决方案1】:

    使用 libcurl

    使用CURLOPT_WRITEFUNCTION 设置写回调。该函数需要解析边界字符串的传入数据并保持状态。当它接收到第二个边界字符串时,它会返回一个错误并且 curl 将停止传输。

    伪代码:

    write_callback
    {
       store_incoming_data(downloaded);
       num_boundaries = boundary_count(downloaded);
       if (num_boundaries >= 2 ) {
          /* we have enough, end it here */
          return error;
       }
       return success; /* continue */
    }
    

    使用卷曲工具

    统计接收到的边界字符串,秒后停止读取。我的示例在这里使用 awk,但您也可以使用您喜欢的任何其他工具:

    curl https://example.com | awk '/^--boundary/ {a++; if(a>1) exit;} {print $0}'
    

    【讨论】:

    • 第一个问题是 curl 函数是在程序内部使用的,而不是在命令行中使用。所以我没有 awk 那里。第二个是 curl 永远不会返回。所以,我留在 perform 函数中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-29
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    相关资源
    最近更新 更多