1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <ArduinoJson.h> // 必须是5 不能安装v6 // 测试HTTP请求用的URL。注意网址前面必须添加"http://" #define URL "http://192.168.8.104:8080/findByDetection" #define POSTURL "http://192.168.8.104:8080/findByDetection" // 设置wifi接入信息(请根据您的WiFi信息进行修改) const char* ssid = "cxy"; const char* password = "12345678"; void setup() { //初始化串口设置 Serial.begin(9600); //设置ESP8266工作模式为无线终端模式 WiFi.mode(WIFI_STA); //开始连接wifi WiFi.begin(ssid, password); //等待WiFi连接,连接成功打印IP while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(""); Serial.print("WiFi Connected!"); httpClientRequest(); } void loop() { // httpClientRequest(); // delay(1000); } // 发送HTTP请求并且将服务器响应通过串口输出 void httpClientRequest(){ //重点1 创建 HTTPClient 对象 HTTPClient httpClient; //重点2 通过begin函数配置请求地址。此处也可以不使用端口号和PATH而单纯的 httpClient.begin(URL); Serial.print("URL: "); Serial.println(URL); //重点3 通过GET函数启动连接并发送HTTP请求 int httpCode = httpClient.GET(); Serial.print("Send GET request to URL: "); Serial.println(URL); DynamicJsonDocument doc(1024); //重点4. 如果服务器响应HTTP_CODE_OK(200)则从服务器获取响应体信息并通过串口输出 //如果服务器不响应HTTP_CODE_OK(200)则将服务器响应状态码通过串口输出 if (httpCode == HTTP_CODE_OK) { // 使用getString函数获取服务器响应体内容 String responsePayload = httpClient.getString(); Serial.println("Server Response Payload: "); if(responsePayload.length() !=0) { Serial.println(responsePayload); deserializeJson(doc, responsePayload); JsonObject obj = doc.as<JsonObject>(); int id = obj["id"]; Serial.println(id); httpClient.end(); httpAdd(id); }else { httpClient.end(); } } else { Serial.println("Server Respose Code:"); Serial.println(httpCode); } //重点5. 关闭ESP8266与服务器连接 httpClient.end(); } /** * 处理写入数据 */ void httpAdd(int id){ HTTPClient httpClient; httpClient.begin(URL); //这句话非常的重要否则无法post到服务器上参数无法取得。 httpClient.addHeader("Content-Type", "application/x-www-form-urlencoded"); int httpCode = httpClient.POST("id="+id+"&po=333333"); if (httpCode > 0) { if (httpCode == HTTP_CODE_OK) { String httpString = httpClient.getString(); Serial.println("getString:"+httpString); } } httpClient.end(); Serial.println("写入数据"); Serial.println(id); } |