esp8266 esp32使用http post往flask发送json数据以及解析json

平台

esp32 +vscode + platformio

引脚:

/** PIN **
 * OLED:VCC  --- ESP32:3.3V
 * OLED:GND  --- ESP32:GND
 * OLED:SCL  --- ESP32:D22
 * OLED:SDA  --- ESP32:D21
 * * 
 * */

需要安装的库

#include "HTTPClient.h"
#include <ArduinoJson.h>

难点

网上很多都是使用http get, 很少用http post的,但是往服务器传数据一般都是post

直接上代码

#include <Arduino.h>
#include "HTTPClient.h"
#include <ArduinoJson.h>

/** PIN **
 * OLED:VCC  --- ESP32:3.3V
 * OLED:GND  --- ESP32:GND
 * OLED:SCL  --- ESP32:D22
 * OLED:SDA  --- ESP32:D21
 * * 
 * */

const char *ssid = "LinuxRT";                      //wifi名
const char *password = "88888888";              //wifi密码
const char *host = "http://192.168.31.221:5000"; 
const char *query_addr = "/upload_data";

WiFiClient wifi_Client;
HTTPClient http_client;
String req;
String rsp;
 

//Wifi连接
void setupWifi()
{
  delay(10);
  Serial.println("connecting WIFI");
  WiFi.begin(ssid, password);
  while (!WiFi.isConnected())
  {
    Serial.print(".");
    delay(500);
  }
  Serial.println("Wifi connected ok!");
}
 
void setUpHttpClient()
{
  req = (String)host + query_addr;
  Serial.println(req);
  if (http_client.begin(req))
  {
    Serial.println("HTTPclient setUp done!");
  }
}
 
void setup()
{
  Serial.begin(115200);
  delay(3000);
  setupWifi();
  setUpHttpClient();
}
 
void loop()
{
  uint8_t buffx[]="hello world";
  
  // 转换为json
  StaticJsonDocument<200> doc;
  doc["current"] = 1;
  String ouput;
  // 序列化
  serializeJsonPretty(doc, ouput);

  // 添加http头
  http_client.addHeader("Content-Type","application/json");
  // 发送请求
  int http_code = http_client.POST((uint8_t*)ouput.c_str(),ouput.length());
  if(http_code == 200)
  {
      rsp = http_client.getString();


      DynamicJsonDocument doc(1024);
      // json序列化
      deserializeJson(doc, rsp);
      JsonObject obj = doc.as<JsonObject>();
      // 获得key
      String state = obj["state"];
      Serial.println(state);
  }
  delay(1000);
}

flask服务器核心代码

@app.route('/upload_data',methods=['POST', 'GET'])
def hello_world1_post():
    data = request.get_json()
    print(data['current'])

    return jsonify({"state": "ok"})

下载地址:https://github.com/KiritoGoLeon/esp_project/tree/master/esp32_current_mearuse

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值