ESP32 HTTPS 简单 GET 请求

我正在尝试使用 HTTPS 改进我的项目,并且我想使用 ESP32 对此测试服务器执行一个简单的 HTTPS 获取请求:

https://pcsvision-a.ddns.net:12347

这是我的代码

#include <HTTPClient.h>

const char* ssid = "DSRSB2-1701 2.4Ghz";
const char* password =  "DSR112233";

void setup() {

  Serial.begin(115200);
  delay(1000);

  WiFi.begin(ssid, password); 

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");
}

const char* root_ca= 
"-----BEGIN CERTIFICATE-----n"
"MIIF1zCCA7+gAwIBAgIUTTXGz/9tVfCXMouYk5WriH8sQUQwDQYJKoZIhvcNAQELn"
"BQAwezELMAkGA1UEBhMCTVkxETAPBgNVBAgMCFNFTEFOR09SMQ4wDAYDVQQHDAVLn"
"QVBBUjEiMCAGA1UECgwZTHVtaW5hbmNlIFN5c3RlbXMgU2RuIEJoZDElMCMGCSqGn" 
"SIb3DQEJARYWaGVsbG9AbHVtaW5hbmNlc3lzLmNvbTAeFw0yMTA3MTEwNzQzNDNan"
"Fw0yMjA3MTEwNzQzNDNaMHsxCzAJBgNVBAYTAk1ZMREwDwYDVQQIDAhTRUxBTkdPn"
"UjEOMAwGA1UEBwwFS0FQQVIxIjAgBgNVBAoMGUx1bWluYW5jZSBTeXN0ZW1zIFNkn"
"biBCaGQxJTAjBgkqhkiG9w0BCQEWFmhlbGxvQGx1bWluYW5jZXN5cy5jb20wggIin"
"MA0GCSqGSIb3DQEBAQUAA4ICDwAwggIKAoICAQDLKpuUjDg8u0pitLtS8coz5RFen"
"iSr64hCarEX/PlnrvtGe5Hv/FYnupU5hAgCQ46/n3Qf4ZfyImLa058/YSyFs7tEbn"
"rI7z5Scx+6Nh1O7I9YVf+6A1GPVE6hAmZrIaJ3AP+APuPb+r4wWLtk/RN1a+kKdIn"
"Jn02MA1FaE5z8Q7QWI0urI8Nq2t/lbj+5BjWxJ+S8lUzkpPV0Ifv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PCkTAdI9E5oN8Ph5qIsVjiOqQqIRD0VioYTn"
"lILQYq/zfA4aLKr0dQbkl3CloDqVNgDNoQgjb9dBsPyJ9AfcSvls5mWbcHvtBy1Un"
"Xe27/NF0n8wVUI4gmbN1dxPPjp/fzVxb4sn6kxU3muMW2cvt4urv6xHlMUK2r/iOn"
"Z6ibzHChoMPaSrRcb8GNYcYjmTJaTaD+wN3ycFJZmiILfeD6LPkO8RvcPUIOA37qn"
"FOdh33OWUAteb/0iK9q/RXE2wJKldwZ6b2SnaaFi5aGXKEfvPbI4gAnRkDB4TCqrn"
"M3kcM8AMKKWIRuw=n"
"-----END CERTIFICATE-----n";

void loop() {

  if ((WiFi.status() == WL_CONNECTED)) { 

    HTTPClient http;

    http.begin("https://pcsvision-a.ddns.net:12347", root_ca); 
    int httpCode = http.GET();                                                  

    if (httpCode > 0) { 

        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }

    else {
      Serial.println("Error on HTTP request");
    }

    http.end(); //Free the resources
  }

  delay(3000);
}

我从串行监视器收到此错误

Connecting to WiFi..
Connecting to WiFi..
Connecting to WiFi..
Connected to the WiFi network
[E][ssl_client.cpp:36] _handle_error(): [start_ssl_client():216]: (-9984) X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -9984
[W][HTTPClient.cpp:1417] returnError(): error(-1): connection refused
Error on HTTP request
[E][ssl_client.cpp:36] _handle_error(): [start_ssl_client():216]: (-9984) X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -9984
[W][HTTPClient.cpp:1417] returnError(): error(-1): connection refused
Error on HTTP request
[E][ssl_client.cpp:36] _handle_error(): [start_ssl_client():216]: (-9984) X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
[E][WiFiClientSecure.cpp:133] connect(): start_ssl_client: -9984
[W][HTTPClient.cpp:1417] returnError(): error(-1): connection refused
Error on HTTP request

我还在学习,非常感谢您的帮助..

你不需要阅读下一个我不能在不添加更多单词的同时发布这个问题我不想浪费你的时间..我希望我的问题是重点

stack overflow ESP32 HTTPS simple GET request
原文答案

答案:

作者头像

下面的代码片段来自我最近编写的用于 Tensilica 的 Xtensa LX6/7 兼容 MCU (ESP32) 的固件代码。下面的代码使用 WIFIClientsecure 库向 Dataverse 存储库 ( dataverse.org ) 发出 HTTPS GET 请求。

完整的代码可以在这里找到:

https://github.com/aeonSolutions/openScienceResearch-Smart-DAQ-Device-able-to-Upload-Live-Experimental-Sensor-Data-to-a-Data-Repo

使用 HTTPClient

 String GetInfoFromDataverse2(String url) {
  if(WiFi.status() != WL_CONNECTED){
    mserial.printStrln("WiFi Disconnected");
    if (connect2WIFInetowrk()){
      GetInfoFromDataverse(url);
    }
  }

  mserial.printStrln("URL: " + url);

  HTTPClient http;

    http.begin("https://" + SERVER_URL + url, HARVARD_ROOT_CA_RSA_SHA1); //Specify destination for HTTP request
    http.addHeader("Host", SERVER_URL);
    http.addHeader("Content-Type", "text/plain");
    //http.addHeader("X-Dataverse-key",  API_TOKEN);
    http.addHeader("Accept", "text/html,application/xhtml+xml,application/xml,application/json");
    http.addHeader("Accept-Encoding", "gzip,deflate" );
    http.addHeader("Accept-Charset", "ISO-8859-1,utf-8" );
    http.addHeader("User-Agent", "AeonLabs LDAD Smart DAQ device" );
    //http.addHeader("Keep-Alive", "300" );
    //http.addHeader("Connection", "keep-alive" );
    http.addHeader("Accept-Language", "en-us" );
    http.addHeader("Connection", "close" );    

    String payload="";
    int httpCode = http.GET();
    mserial.printStrln("");
    mserial.printStrln("HTTP Code: " + String(httpCode));
    if (httpCode > 0) { //Check for the returning code
        payload = http.getString();
        mserial.printStrln(payload);
    }

    return String(payload);
}

使用 WIFIclientsecure

String GetInfoFromDataverse(String url) {
  //Check WiFi connection status

  if(WiFi.status() != WL_CONNECTED){
    mserial.printStrln("WiFi Disconnected");
    if (connect2WIFInetowrk()){
      GetInfoFromDataverse(url);
    }
  }

  int str_len = SERVER_URL.length() + 1; // Length (with one extra character for the null terminator)
  char SERVER_URL_char [str_len];    // Prepare the character array (the buffer) 
  SERVER_URL.toCharArray(SERVER_URL_char, str_len);    // Copy it over 

  client.stop();
  client.setCACert(HARVARD_ROOT_CA_RSA_SHA1);

  if (!client.connect(SERVER_URL_char, SERVER_PORT)) {
      mserial.printStrln("Cloud server URL connection FAILED!");
      mserial.printStrln(SERVER_URL_char);
      int server_status = client.connected();
      mserial.printStrln("Server status code: " + String(server_status));
      return "";
  }

  mserial.printStrln("Connected to the dataverse of Harvard University"); 
  mserial.printStrln("");

  // We now create a URI for the request
  mserial.printStr("Requesting URL: ");
  mserial.printStrln(url);

  // Make a HTTP request and add HTTP headers    
  // post header
  String postHeader = "GET " + url + " HTTP/1.1rn";
  postHeader += "Host: " + SERVER_URL + ":" + String(SERVER_PORT) + "rn";
  //postHeader += "X-Dataverse-key: " + API_TOKEN + "rn";
  postHeader += "Content-Type: text/jsonrn";
  postHeader += "Accept: text/html,application/xhtml+xml,application/xml,application/json,text/json;q=0.9,*/*;q=0.8rn";
  postHeader += "Accept-Encoding: gzip,deflatern";
  postHeader += "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7rn";
  postHeader += "User-Agent: AeonLabs LDAD Smart DAQ devicern";
  //postHeader += "Keep-Alive: 300rn";
  postHeader += "Accept-Language: en-usrn";
  postHeader += "Connection: closernrn";

  // request tail
  String boundary = "7MA4YWxkTrZu0gW";
  String tail = "rn--" + boundary + "--rnrn";

  // content length
  int contentLength = tail.length();
  //postHeader += "Content-Length: " + String(contentLength, DEC) + "nn";

  // send post header
  int postHeader_len=postHeader.length() + 1; 
  char charBuf0[postHeader_len];
  postHeader.toCharArray(charBuf0, postHeader_len);
  client.print(charBuf0);

  mserial.printStrln("======= Headers =======");
  mserial.printStrln(charBuf0);
  mserial.printStrln("======= End of Headers =======");

  // Read all the lines of the reply from server and print them to mserial
  String responseHeaders = "";

  mserial.printStr("Waiting for server response...");
  long timeout= millis();
  long ttl=millis()-timeout;
  while (client.connected() && abs(ttl) < 30000) { // 30 sec.
    ttl=millis()-timeout;      
    responseHeaders = client.readStringUntil('n');
    if (responseHeaders == "r") {
      break;
    }
  }
  if (abs(ttl) < 10000){
    mserial.printStrln("OK");
  }else{
    mserial.printStrln("timed out.");  
  }

  String responseContent = client.readStringUntil('n');
  client.stop();

  return responseContent;
  }