我正在尝试使用NodeMCU示例客户端代码向我的网站发送标准的http GET请求,但由于某种原因它无法正常工作。
如果我输入我的浏览器:snackrefill.com/GetData.php?username=aaaa&pin=bbbb&cost=cccc
那么它将成功连接php脚本并保存数据库条目。
问题在于,当我尝试使用NodeMCU模块执行相同操作时,它不起作用。它似乎连接到WiFi和服务器就好了但是当它发送请求时似乎没有发生任何事情。
我是否错误地构建了我的请求?
#include <ESP8266WiFi.h>
const char* ssid = "BELL473";
const char* password = "XXXXXXX";
const char* host = "ns8451.hostgator.com";
void setup() {
Serial.begin(115200);
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password); //works!
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
int value = 0;
void loop() {
delay(5000);
++value;
Serial.print("connecting to ");
Serial.println(host);
// Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
if (!client.connect(host, httpPort)) { //works!
Serial.println("connection failed");
return;
}
// We now create a URI for the request
String url = "/GetData.php";
url += "?username=";
url += "aaaa";
url += "&pin=";
url += "bbbb";
url += "&cost=";
url += "cccc";
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");
}
答案 0 :(得分:2)
它不发送的原因是因为主机错了,我指的是我的网站名称服务器,当我应该指向常规网站名称时。我将const char* host = "ns8451.hostgator.com";
更改为const char* host = "snackrefill.com";
,现在就可以了!