如何使用 Nodemcu - Arduino 代码发送 HTTPS - GET/POST 请求。
我花了几天时间寻找一个使用 HTTPS 协议向网站发送 GET 请求的工作示例,但我找到的所有示例均不成功。
我希望它也能帮助其他人!
要使示例适用于 HTTPS 协议,您必须使用
WiFiClientSecure
库并调用您拥有的 client.setInsecure()
对象的 WiFiClientSecure
函数。
这是一个完整的工作代码:
#include <ESP8266WiFi.h>
const char* ssid = "WIFI_SSID";
const char* password = "WIFI_PASS";
const char* host = "DOMAIN_NAME"; // only google.com not https://google.com
void setup() {
Serial.begin(115200);
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
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());
}
void loop() {
delay(5000);
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClientSecure client;
const int httpPort = 443; // 80 is for HTTP / 443 is for HTTPS!
client.setInsecure(); // this is the magical line that makes everything work
if (!client.connect(host, httpPort)) { //works!
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/arduino.php";
url += "?data=";
url += "aaaa";
Serial.print("Requesting URL: ");
Serial.println(url);
// This will send the request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println();
Serial.println("closing connection");
}
你找到答案了吗?我希望在执行 GET 查询时获取数据作为回报。你能帮忙吗?