如何在ESP的WifiClientSecure中设置请求标头

时间:2019-11-08 07:06:04

标签: https arduino request esp8266

我想在我的ESP8266上进行具有承载授权的HTTPS PUT请求,但无法正常工作。

我试图刷新自定义固件(Espruino,带有HTTPS支持的自定义NodeMcu)并使用不同的库(HttpClient,WifiClient,WifiClientSecure),但是没有成功。

我也尝试了大量的代码示例,但是很难找到具有HTTPS支持的示例。 这是我使用的示例之一:

    #include <ESP8266WiFi.h>
    #include <WiFiClientSecure.h>

    #ifndef STASSID
    #define STASSID "xxxx"
    #define STAPSK  "xxxx"
    #endif

const char* ssid = STASSID;
const char* password = STAPSK;

const char* host = "api.github.com";
const int httpsPort = 443;

// Use web browser to view and copy
// SHA1 fingerprint of the certificate
const char fingerprint[] PROGMEM = "59:74:61:88:13:CA:12:34:15:4D:11:0A:C1:7F:E6:67:07:69:42:F5";

void setup() {
  Serial.begin(115200);
  Serial.println();
  Serial.print("connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  // Use WiFiClientSecure class to create TLS connection
  WiFiClientSecure client;
  Serial.print("connecting to ");
  Serial.println(host);

  Serial.printf("Using fingerprint '%s'\n", fingerprint);
  client.setFingerprint(fingerprint);

  if (!client.connect(host, httpsPort)) {
    Serial.println("connection failed");
    return;
  }

  String url = "/repos/esp8266/Arduino/commits/master/status";
  Serial.print("requesting URL: ");
  Serial.println(url);

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "User-Agent: BuildFailureDetectorESP8266\r\n" +
               "Connection: close\r\n\r\n");

  Serial.println("request sent");
  while (client.connected()) {
    String line = client.readStringUntil('\n');
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  String line = client.readStringUntil('\n');
  if (line.startsWith("{\"state\":\"success\"")) {
    Serial.println("esp8266/Arduino CI successfull!");
  } else {
    Serial.println("esp8266/Arduino CI has failed");
  }
  Serial.println("reply was:");
  Serial.println("==========");
  Serial.println(line);
  Serial.println("==========");
  Serial.println("closing connection");
}

因此,最后,ESP应该使用承载者身份验证连接到我的Mozilla WebThings网关,并通过PUT通过HTTPS连接更改值。

总结的问题是:

  • 如何为PUT请求添加有效载荷
  • 如何添加请求标头

任何帮助(尤其是代码示例)将不胜感激。

0 个答案:

没有答案