esp8266httpclient_get_post使用

esp8266httpclient_get_post使用

#include<ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

//const char *ssid = "AxxxIFI";
const char *password = "xxxs879xxx68";
 const char* ssid = "IT-nxxxang";
 

 
const char* URL = "http://172.127.5.27:927/";   // 测试HTTP请求用的URL。注意网址前面必须添加"http://"
const char* post_string = "{\"robot_id\":1}";
 
void setup() {
  Serial.begin(115200);  //启动串口,并设置波特率为115200
  connectWiFi();        //连接WiFi
  httpClientRequest();  //通过客户端发送http请求,并响应
}
 
void loop() {
   httpClientRequest();  //通过客户端发送http请求,并响应
   delay(5000);
}

 
void httpClientRequest(){
  HTTPClient httpClient;          //1、创建http的客户端
  httpClient.begin(URL);          //2、通过begin函数配置请求地址。此处也可以不使用端口号
  Serial.print("URL: "); 
  Serial.println(URL);
  //int httpCode = httpClient.GET();  //3、通过GET函数启动连接并发送HTTP请求
  int httpCode = httpClient.POST(post_string);
  if (httpCode > 0) {
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    if (httpCode == HTTP_CODE_OK) {
      String payload = httpClient.getString();    //获取响应体
      Serial.println(payload);
    } else {
      Serial.printf("[HTTP] GET... failed, error: %s\n", httpClient.errorToString(httpCode).c_str());
    }
  } else {
    Serial.printf("[HTTP] Unable to connect\n");
  }
  httpClient.end();
}
 
void connectWiFi(){
  Serial.println();
  Serial.print("Connecting to");
  Serial.println(ssid);
  WiFi.begin(ssid,password);                  //启动WIFI
  while(WiFi.status()!=WL_CONNECTED){         //判断WiFi的连接状态,如果没有连接成功,等待
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.print("IP address:");
  Serial.println(WiFi.localIP());    //获取本机的IP
}

猜你喜欢

转载自blog.csdn.net/txwtech/article/details/132208898
今日推荐