我需要使用HTTP进行简单的GET调用。尽管已成功连接到WiFi网络,并正确获取了IP,网关和DNS,但HTTP客户端仍保持连接失败错误。我也尝试使用WiFi客户端,但是没有运气。它不认为问题出在我的代码上,我也尝试使用examples文件夹中的代码,但它也失败了。我尝试连接到本地内部服务器,但失败了。我花了整整一整天的时间,无法弄清楚到底是怎么回事。
代码如下。这就是目前的所有内容。
我正在Windows上使用Visual Code Editor在Platform IO上使用Arduino for ESPRESSIF。
从setup()调用WifiConnect函数
最初,我只调用WiFi.begin()函数进行连接,该功能也与WiFi连接,但是由于连接失败,我根据示例代码尝试了ESP8266WiFiMulti。
我什至检查了主机名解析是否也有效
IPAddress remote_addr;
WiFi.hostByName("192.168.2.107", remote_addr);
Serial.println(remote_addr);
但是连接到任何服务器总是失败。我尝试连接到网络内部的服务器,Internet上的服务器,在特殊端口上运行http的服务器,普通端口80等。但是它顽固地拒绝连接。
#include "Arduino.h"
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include "Ticker.h"
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti WiFiMulti;
void WifiConnect()
{
WiFi.mode(WIFI_STA);
WiFiMulti.addAP("MySSID", "MySECret Password");
Serial.print("Connecting");
while (WiFiMulti.run() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.dnsIP());
Serial.println(WiFi.gatewayIP());
Serial1.println(WiFi.localIP());
}
void logToThinkSpeakt(){
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED)) {
WiFiClient client;
HTTPClient http;
Serial.print("[HTTP] begin...\n");
if (http.begin(client, "http://jigsaw.w3.org/HTTP/connection.html")) { // HTTP
Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if (httpCode > 0) {
// HTTP header has been send and Server response header has been handled
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
String payload = http.getString();
Serial.println(payload);
}
} else {
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
} else {
Serial.printf("[HTTP} Unable to connect\n");
}
}
}
平台:Espressif 8266 2.6.2> NodeMCU 1.0(ESP-12E模块) 硬件:ESP8266 80MHz,80KB RAM,4MB Flash 包装: