使用正则表达式从服务器回复中删除 HTML header

Remove HTML header from server reply using Regular Expressions

我有一个集成了 GSM-unit 的 ESP32 T-CALL 并使用 this 作为 Arduino IDE 的基础 IDE。

我的代码生成 server-call 并处理结果。此代码从缓冲区读取并将其输出到字符串。它使用手动生成的 POST header,串行发送。但是,我需要删除 HTTP header,只留下 JSON.

while (client.connected() && millis() - timeout < 10000L) {
  // Print available data (HTTP response from server)
  while (client.available()) {
    char c = client.read();
    returnString += c;
    timeout = millis();
  }
}

输出自带一个完整的header,像这样:

HTTP/1.1 200 OK
Content-Type: application/json
Server: Microsoft-IIS/10.0
X-Powered-By: PHP/8.0.0
X-Powered-By: ASP.NET
Date: Tue, 25 Jan 2022 00:12:31 GMT
Connection: close
Content-Length: 23

{"status:":"code6"}

我使用 <regexp.h> library by Nick Gammon and the Lua-reference here 来过滤掉大括号左侧的所有内容 - 但是,我似乎无法正确处理。我想,是这样的:

char result = ms.Match ("{(%x+)"); // Find the first curlybrace and only include this and everything to the right.

唉,用这个正则表达式,找不到匹配项。我也尝试在 \r\n\r\n、using the getValue-function here 处拆分,但无法让它接受双换行符。

关于如何使用 RegEx 删除 header 有什么想法吗?

这不是关于如何使用正则表达式的直接答案,但是,如果您想跳过 headers 并获取负载,而不是使用正则表达式或我建议的 httpclient 库评论,不使用任何库也不难做到。

要跳过 header 并获取有效负载,您需要修改代码以找到 header 的结尾。


// skip the http headers
while (client.connected()) {
  String line = client.readStringUntil('\n');
  if (line == '\r') break;    //if line only contain '\r', it's the end of headers
  }
}

// get the payload
String payload;
while (client.available()) {
  payload = client.readStringUntil('\n');
}

然后您可以使用 JSON 库从 JSON object 中提取数据。或者如您所示的简单 JSON object,您可以在没有库的情况下完成。

payload.trim();                  // remove the '\r\n' at the end
payload.replace("status:", "");  // replace "status:" with ""
payload.replace("\"", "");       // remove all the "\""
payload.trim();
Serial.println(payload);

这将在您的 JSON object 中打印出 code6 的值。