编写程序esp8266处理一个带参数的get请求
时间: 2023-07-15 15:13:23 浏览: 45
以下是一个ESP8266处理带参数的GET请求的示例程序:
```c
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
const char* ssid = "your_SSID";
const char* password = "your_WIFI_password";
const char* host = "your_server.com";
const int httpPort = 80;
void setup() {
Serial.begin(115200);
delay(10);
// Connect to WiFi
Serial.println();
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() {
WiFiClient client;
if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return;
}
String url = "/path/to/your/api?key=value"; // Replace with your API URL and parameters
Serial.print("Requesting URL: ");
Serial.println(url);
// Send GET request to the server
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
// Wait for response from the server
while (!client.available()) {
delay(10);
}
// Read response from the server
while (client.available()) {
String line = client.readStringUntil('\r');
Serial.print(line);
}
Serial.println();
Serial.println("closing connection");
}
```
在 `url` 变量中,替换为你的 API URL 和参数。例如,如果你的 API URL 是 `http://your_server.com/api.php`,参数是 `key=value`,则将 `url` 设置为 `/api.php?key=value`。
此代码发送 GET 请求并打印响应。你可以根据需要修改它来将响应解析为所需的格式。