乐鑫技术交流
直播中

刘军

8年用户 1480经验值
私信 关注
[问答]

HTTPClient API响应问题如何解决?

我正在尝试访问我的 Wemos D1 mini 上的 API ( https://api.coronavirus.data.gov.uk ),并对 JSON 数据执行一些操作。问题:HTTP 客户端正在取回压缩的页面内容(例如“^_<8b>^H^@.Hï_^BÿíÙÁjÃ0^L^Fàw”)。我想我现在已经将其识别为 gzip 压缩内容,方法是在带有 --compressed 标志的 cURL 中尝试它——这成功地解码了内容。我无法弄清楚的奇怪部分是,对于其他 API(例如 github)- 内容根据标头进行 gzip 压缩,但在 D1 mini 上解压缩后返回,因此读取它没有问题。有人可以帮忙吗?

代码:全选#include
#include
#include
#include
#include

const char* host = \"https://api.coronavirus.data.gov.uk\";
// const char* host = \"https://api.github.com\";

int httpsPort = 443;

const char* ssid = \"ssid\";
const char* password = \"password\";

void setup(void){
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println(\"\");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(\".\");
  }
  Serial.println(\"\");
  Serial.print(\"Connected to \");
  Serial.println(ssid);
  Serial.print(\"IP address: \");
  Serial.println(WiFi.localIP());
}

void loop() {

  WiFiClientSecure client;
  client.setInsecure(); //the magic line, use with caution
  client.connect(host, httpsPort);

  HTTPClient https;  

    Serial.print(\"[HTTPS] begin...\\n\");
    if (https.begin(client, \"https://api.coronavirus.data.gov.uk/v1/data?filters=areaType=nation;areaName=england&structure=%7B%22name%22:%22areaName%22%7D\")) {  // HTTPS
//    if (https.begin(client, \"https://api.github.com\")) {  // HTTPS

      Serial.print(\"[HTTPS] GET...\\n\");
      // start connection and send HTTP header
      int httpCode = https.GET();

      // httpCode will be negative on error
      if (httpCode > 0) {
        // HTTP header has been send and Server response header has been handled
        Serial.printf(\"[HTTPS] GET... code: %d\\n\", httpCode);

        // file found at server
        if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
          String payload = https.getString();
          Serial.println(payload);
        }
      } else {
        Serial.printf(\"[HTTPS] GET... failed, error: %s\\n\", https.errorToString(httpCode).c_str());
      }

      https.end();
    } else {
      Serial.printf(\"[HTTPS] Unable to connect\\n\");
    }


  Serial.println(\"Wait 20s before next round...\");
  delay(200000);
}

更多回帖

发帖
×
20
完善资料,
赚取积分