欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HTTP协议数据通讯-客户端向服务器发送数据信息-客户端

程序员文章站 2024-03-23 09:45:04
...

HTTP协议数据通讯-客户端向服务器发送数据信息-客户端

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#define buttonPin D3//定义引脚D3

ESP8266WiFiMulti wifiMulti;

bool buttonStatus;
float clientFloatValue;
int clientIntValue;

const char *host = "192.168.0.111";
const int httpPort = 80;

void setup(){
  Serial.begin(9600);
  Serial.println("");

  pinMode(buttonPin,INPUT_PULLUP);//将按键设置为输入上拉模式

  wifiMulti.addAP("1124","11241124");

  while(wifiMulti.run() != WL_CONNECTED){
    delay(250);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Wifi Connected to :\t");
  Serial.println(WiFi.SSID());
  Serial.print("IP Address:\t");
  Serial.println(WiFi.localIP());
}

void loop(){
  buttonStatus = digitalRead(buttonPin);

  //改变测试用变量数值用于服务端接收数据检测
  clientFloatValue += 1.5;
  clientIntValue += 2;

  //发送请求
  wifiClientRequest();
  delay(1000);
}

void wifiClientRequest(){
  WiFiClient wifiClient;

  //将需要发送的数据信息放入客户端请求
  String url = "/update?float="+ String(clientFloatValue)+"&int="+String(clientIntValue)+"&button="+String(buttonStatus);

  //建立字符串,用于http请求
  String httpRequest = String("GET ") + url + "HTTP/1.1\r\n"+"Host: "+host+"\r\n"+"Connection:close\r\n"+"\r\n";
  Serial.print("Connecting to :\t");
  Serial.print(host);

  if(wifiClient.connect(host,httpPort)){
    Serial.println(" Success");

    wifiClient.print(httpRequest);//向服务器发送http请求
    Serial.print("Sending request: ");
    Serial.println(httpRequest);
  }else{
    Serial.println(" Failed");
  }
  wifiClient.stop();
}

相关标签: ESP8266 ESP8266