ESP8266访问https地址,ESP32

做了一个小项目,使用的ESP8266 访问https地址来上传数据(虽然直接使用TCP连接来传可能更方便,但对方要求通过访问https我也只能照做)arduino中有ESP8266HTTPClient来进行http和https连接,http连接则比较简单,直接使用示例程序修改即可,而https还需要验证网站指纹证书。实际使用如下

void http_post() {
  date_str = (char *) malloc(strlen(URL) +7 );
  sprintf(date_str, "%s%s%c%s",URL,temc,'/',humc);//合成访问地址
  Serial.println(date_str);
    std::unique_ptr<BearSSL::WiFiClientSecure>client(new BearSSL::WiFiClientSecure);
    client->setFingerprint(fingerprint);
    HTTPClient https;//根据访问地址的协议来选择使用http还是https,用https就需要使用网站的证书
    Serial.print("[HTTPS] begin...\n");
    if (https.begin(*client, date_str)) {  // 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");
    }

}

date_str就是最终的访问地址,fingerprint就是需要验证的网站指纹证书,格式如下

const uint8_t fingerprint[20] = {0xDE, 0x17, 0x1D, 0xD8, 0xC0, 0xE9, 0xDF, 0x28 ,0xB3 ,0xCD ,0x38 ,0x0E ,0x80 ,0xA4 ,0x2A ,0xF3
,0x28 ,0xC3 ,0x28 ,0x4E};//网站证书指纹

具体如何获取可以借用浏览器来获取,比如访问https://www.baidu.com/

首先使用浏览器打开(可用edge,Chrome,这里用的edge)

点击锁的图形,然后点击连接安全选项,再点右上方的证书图形

点开后就可以看到网站的指纹证书了

我们需要的是SHA-1,把这串指纹填入我们程序就行了(记得改好格式,16进制就需要加0x)

猜你喜欢

转载自blog.csdn.net/hhcgn/article/details/129410328