WiFiClientInsecure

はじめに

HTTPSを利用して、ウェブサーバにアクセスします。ただし、証明書による検証は行いません。

プログラム

定義等

1
2
3
4
5
6
7
8
9
#include <WiFiClientSecure.h>

const char* ssid     = "your-ssid";     // your network SSID (name of wifi network)
const char* password = "your-password"; // your network password

const char*  server = "www.howsmyssl.com";  // Server URL

WiFiClientSecure client;
 

ssidとpasswordは、WiFiアクセス用のSSID/パスフレーズです。

serverは、アクセスするウェブサーバです。

client は、WiFiClientSecure型の変数で、HTTPSで接続する際に用います。

setup()

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(115200);
  delay(100);

  Serial.print("Attempting to connect to SSID: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);

  // attempt to connect to Wifi network:
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    // wait 1 second for re-trying
    delay(1000);
  }

  Serial.print("Connected to ");
  Serial.println(ssid);

  Serial.println("\nStarting connection to server...");
  client.setInsecure();//skip verification
  if (!client.connect(server, 443))
    Serial.println("Connection failed!");
  else {
    Serial.println("Connected to server!");
    // Make a HTTP request:
    client.println("GET https://www.howsmyssl.com/a/check HTTP/1.0");
    client.println("Host: www.howsmyssl.com");
    client.println("Connection: close");
    client.println();

    while (client.connected()) {
      String line = client.readStringUntil('\n');
      if (line == "\r") {
        Serial.println("headers received");
        break;
      }
    }
    // if there are incoming bytes available
    // from the server, read them and print them:
    while (client.available()) {
      char c = client.read();
      Serial.write(c);
    }

    client.stop();
  }
}
 

WiFi.begin()により、ssidで指定したアクセスポイントに接続します。この際のパスフレーズは、passwordです。WiFiは、WiFi.cppで定義されている変数です。

WiFi.status()は、現在の接続状態を返却します。アクセスポイントに接続しているときは、WL_CONNECTEDが返ってきます。

client.setInsecure()で、HTTPS接続する際、証明書による検証を行わないよう指示します。

client.connect()を利用して、指定したホストの、指定したポートに接続します。connect()は成功したときに1を返します。

client.println()で、HTTPリクエストを書き込みます。WiFiClientSecureは、Printクラスを継承しているので、Serialと同じように、println()などを利用することができます。

client.connected()は、サーバとの接続状態を返却します。接続している間は、while文内を実行します。

WiFiClientSecureは、Streamクラスも継承しているので、readStringUntil()が利用できます。

client.available()は、読み込み可能なバイト数を返却します。

client.read()は、サーバから1文字読み込みます。

client.stop()は、サーバとの接続を切断します。

loop()

59
60
61
void loop() {
  // do nothing
}

何もしません。

バージョン

Hardware:ESP-WROOM-32
Software:Arduino core for the ESP32 2.0.4

最終更新日

September 4, 2022

inserted by FC2 system