https - 如何使用 NODEMCU 发送 HTTPS GET 请求
问题描述
如何使用 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");
}
推荐阅读
- hazelcast - 如何在本地环境中配置 Hazelcast 集群进行测试
- python - Python pandas:合并部分重叠的数据框
- node.js - 设置 nodejs express 响应大小
- android - Android(ReactNative)发布版本在启动后显示白屏
- retrofit2 - 我们什么时候在 Retrofit onFailure() 中得到确切的消息“超时”?
- java - 使用两个进程访问 Kafka 主题
- kubernetes - 如何在一个 k8s 节点上运行多个网络接口?
- ios - 远程通知字符串的本地化会破坏设备设置语言和区域设置 Swift
- javascript - 自定义 Amcharts v4 工具提示边框颜色
- c# - 从 OnActionExecuting 重定向到操作不起作用