简体   繁体   English

使用 NodeMCU ESP8266 发送 GET 请求

[英]Sending GET Request with NodeMCU ESP8266

I'm trying to send a standard http GET request to my website using the NodeMCU example client code however for some reason it is not working.我正在尝试使用 NodeMCU 示例客户端代码向我的网站发送一个标准的 http GET 请求,但是由于某种原因它不起作用。

If I type into my browser: snackrefill.com/GetData.php?username=aaaa&pin=bbbb&cost=cccc then it will successfully connect with the php script and save a data base entry.如果我在浏览器中输入: snackrefill.com/GetData.php?username=aaaa&pin=bbbb&cost=cccc那么它将成功连接 php 脚本并保存一个数据库条目。

The problem is that when I try to do the same using the NodeMCU module it does not work.问题是,当我尝试使用 NodeMCU 模块执行相同操作时,它不起作用。 it seems to be connecting to WiFi and the server just fine but when it sends the request nothing seems to happen.它似乎正在连接到 WiFi 并且服务器很好,但是当它发送请求时似乎什么也没发生。

Am I structuring my request wrong?我的请求结构错误吗?

#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");
}

The reason it was not sending was because the host was wrong, i was pointing to my website nameserver when i should have pointed it to the regular website name.它没有发送的原因是因为主机错误,当我应该将它指向常规网站名称时,我指向了我的网站名称服务器。 I changed const char* host = "ns8451.hostgator.com";我改变了const char* host = "ns8451.hostgator.com"; to const char* host = "snackrefill.com"; const char* host = "snackrefill.com"; and now it works!现在它起作用了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM