본문 바로가기

ESP32

ESP32 HTTP GET 및 HTTP POST와 JSON, URL 인코딩, 텍스트

반응형

 

ESP32 HTTP GET 및 HTTP POST와 Arduino IDE(JSON, URL 인코딩, 텍스트)

 

이 가이드에서는 Arduino IDE가 있는 ESP32 보드로 HTTP GET 및 HTTP POST 요청을 하는 방법을 알아봅니다. 값을 가져오고, JSON 객체를 게시하고, URL 인코딩된 요청을 하는 방법 등에 대한 예를 다룹니다.

 

ESP32 HTTP GET 및 HTTP POST와 Arduino IDE(JSON, URL 인코딩, 텍스트)

 

권장: ESP8266 NodeMCU HTTP GET 및 HTTP POST와 Arduino IDE(JSON, URL 인코딩, 텍스트)

 

HTTP 요청 방법: GET 대 POST

 

  • HTTP(Hypertext Transfer Protocol)는 클라이언트와 서버 간의 요청-응답 프로토콜로 작동합니다. 다음은 예입니다.
  • ESP32(클라이언트)는 Node-RED(서버)를 실행하는 Raspberry Pi에 HTTP 요청을 제출합니다. 서버는 ESP32(클라이언트)에 응답을 반환합니다.
  • 마지막으로 응답에는 요청에 대한 상태 정보가 포함되며 요청된 콘텐츠도 포함될 수 있습니다.

 

HTTP GET

 

GET은 지정된 리소스에서 데이터를 요청하는 데 사용됩니다. API에서 값을 가져오는 데 자주 사용됩니다.

 

예를 들어 다음과 같습니다.

 

GET /update-sensor?temperature=value1

 

쿼리 문자열(name = temperature 및 value = value1)이 HTTP GET 요청의 URL로 전송됩니다.

 

또는 간단한 요청을 사용하여 값이나 JSON 객체를 반환할 수 있습니다(예:

 

GET /get-sensor

(HTTP GET을 사용하면 URL 요청의 모든 사람이 데이터를 볼 수 있습니다.)

 

HTTP POST

 

POST는 리소스를 생성/업데이트하기 위해 서버로 데이터를 전송하는 데 사용됩니다. 예를 들어 센서 판독값을 서버에 게시합니다.

 

POST로 서버로 전송된 데이터는 HTTP 요청의 요청 본문에 저장됩니다.

 

POST /update-sensor HTTP/1.1
Host: example.com
api_key=api&sensor_name=name&temperature=value1&humidity=value2&pressure=value3
Content-Type: application/x-www-form-urlencoded

 

본문 요청에서 JSON 객체를 보낼 수도 있습니다.

 

POST /update-sensor HTTP/1.1
Host: example.com
{api_key: "api", sensor_name: "name", temperature: value1, humidity: value2, pressure: value3}
Content-Type: application/json

 

(HTTP POST를 사용하면 URL 요청에서 데이터가 표시되지 않습니다. 그러나 암호화되지 않은 경우 요청 본문에서 여전히 표시됩니다.)

 

ESP32를 사용한 HTTP GET/POST

 

이 가이드에서는 다음 시나리오를 살펴보겠습니다.

 

1. ESP32 HTTP GET: URL의 값 또는 쿼리

2. ESP32 HTTP GET: JSON 데이터 객체 또는 일반 텍스트

3. ESP32 HTTP POST: URL 인코딩, JSON 데이터 객체, 일반 텍스트

 

필수 조건

 

이 튜토리얼을 진행하기 전에 다음 필수 조건을 완료했는지 확인하세요.

 

Arduino IDE

 

Arduino IDE를 사용하여 ESP32를 프로그래밍하므로 ESP32 애드온이 설치되어 있는지 확인하세요.

Arduino IDE(Windows, Mac OS X, Linux)에 ESP32 보드 설치

 

Arduino_JSON 라이브러리

 

Arduino_JSON 라이브러리도 설치해야 합니다. Arduino IDE 라이브러리 관리자에서 이 라이브러리를 설치할 수 있습니다. 스케치 > 라이브러리 포함 > 라이브러리 관리로 이동하여 다음과 같이 라이브러리 이름을 검색하세요.

 

Arduino JSON 라이브러리 설치 Arduino IDE

 

필요한 부품

이 튜토리얼에서는 다음 부품이 필요합니다.

 

  • ESP32(최고의 ESP32 개발 보드 읽기)
  • Raspberry Pi 보드(최고의 Raspberry Pi 스타터 키트 읽기)
  • MicroSD 카드 - 16GB Class10
  • Raspberry Pi 전원 공급 장치(5V 2.5A)
  • 점퍼 와이어
  • 브레드보드

 

Node-RED 준비(선택 사항)

 

예를 들어, Raspberry Pi와 Node-RED를 사용하여 웹 서비스(API와 같은)로 작동하는 웹 서비스를 만들어 보겠습니다. 기본적으로 Raspberry Pi에 HTTP GET 및 HTTP POST 요청을 보내 값을 가져오거나 업데이트합니다. 다른 웹 서비스를 사용할 수 있습니다.

 

Node-RED가 설치되지 않은 경우 다음 튜토리얼을 따르세요.

 

 

Raspberry Pi에서 Node-RED를 실행하고 Raspberry Pi IP 주소로 이동한 다음 :1880을 입력합니다.

 

http://raspberry-pi-ip-address:1880

 

Node-RED 인터페이스가 열립니다. 간단히 최종 흐름을 가져올 수 있습니다.

 

Node-RED-Flow-HTTP-GET-POST-Request-Methods-ESP32-ESP8266-Arduino

 

메뉴 > 가져오기로 이동하여 다음을 클립보드에 복사하여 Node-RED 흐름을 만듭니다.

 

[{"id":"599740b7.efde9","type":"http response","z":"b01416d3.f69f38","name":"","statusCode":"200","headers":{},"x":420,"y":689,"wires":[]},{"id":"1618a829.76f638","type":"json","z":"b01416d3.f69f38","name":"","property":"payload","action":"obj","pretty":true,"x":410,"y":809,"wires":[["d0089cc7.d25ac"]]},{"id":"c7410fa2.1c2fa","type":"debug","z":"b01416d3.f69f38","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":850,"y":709,"wires":[]},{"id":"75a22f74.f1aba","type":"ui_text","z":"b01416d3.f69f38","group":"2b7ac01b.fc984","order":1,"width":0,"height":0,"name":"","label":"Sensor Name","format":"{{msg.payload}}","layout":"row-spread","x":860,"y":769,"wires":[]},{"id":"1c8f9093.8bc2bf","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"2b7ac01b.fc984","order":2,"width":0,"height":0,"gtype":"gage","title":"Temperature","label":"ºC","format":"{{value}}","min":0,"max":"38","colors":["#00b500","#e6e600","#ca3838"],"seg1":"","seg2":"","x":850,"y":829,"wires":[]},{"id":"a5bd2706.54e108","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"2b7ac01b.fc984","order":3,"width":0,"height":0,"gtype":"gage","title":"Humidity","label":"%","format":"{{value}}","min":0,"max":"100","colors":["#0080ff","#0062c4","#002f5e"],"seg1":"","seg2":"","x":840,"y":889,"wires":[]},{"id":"105ac2cc.7b3cfd","type":"ui_gauge","z":"b01416d3.f69f38","name":"","group":"2b7ac01b.fc984","order":4,"width":0,"height":0,"gtype":"gage","title":"Pressure","label":"hPa","format":"{{value}}","min":0,"max":"1200","colors":["#b366ff","#8000ff","#440088"],"seg1":"","seg2":"","x":840,"y":949,"wires":[]},{"id":"d0089cc7.d25ac","type":"function","z":"b01416d3.f69f38","name":"JSON or URL Encoded","func":"var msg0 = { payload: msg.payload.api_key };\nvar msg1 = { payload: msg.payload.sensor };\nvar msg2 = { payload: msg.payload.value1 };\nvar msg3 = { payload: msg.payload.value2 };\nvar msg4 = { payload: msg.payload.value3 };\n\nreturn [msg0, msg1, msg2, msg3, msg4];","outputs":5,"noerr":0,"x":610,"y":809,"wires":[["c7410fa2.1c2fa"],["75a22f74.f1aba"],["1c8f9093.8bc2bf"],["a5bd2706.54e108"],["105ac2cc.7b3cfd"]]},{"id":"5d9ab0d2.66b92","type":"http in","z":"b01416d3.f69f38","name":"","url":"update-sensor","method":"post","upload":false,"swaggerDoc":"","x":200,"y":740,"wires":[["599740b7.efde9","c7410fa2.1c2fa","1618a829.76f638"]]},{"id":"7f5cf345.63f56c","type":"http response","z":"b01416d3.f69f38","name":"","statusCode":"200","headers":{},"x":540,"y":420,"wires":[]},{"id":"6530621.95b429c","type":"http in","z":"b01416d3.f69f38","name":"","url":"/get-sensor","method":"get","upload":false,"swaggerDoc":"","x":180,"y":600,"wires":[["9471d1a0.68588"]]},{"id":"5ddc9f47.4b555","type":"http response","z":"b01416d3.f69f38","name":"","statusCode":"200","headers":{},"x":540,"y":560,"wires":[]},{"id":"9471d1a0.68588","type":"function","z":"b01416d3.f69f38","name":"","func":"msg.payload = {\"value1\":24.25, \"value2\":49.54, \"value3\":1005.14};\nreturn msg;","outputs":1,"noerr":0,"x":350,"y":600,"wires":[["5ddc9f47.4b555","13aea59.7430e5a"]]},{"id":"13aea59.7430e5a","type":"debug","z":"b01416d3.f69f38","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":550,"y":628,"wires":[]},{"id":"e71c7a7d.e7c598","type":"debug","z":"b01416d3.f69f38","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":550,"y":500,"wires":[]},{"id":"c7807102.3f433","type":"http in","z":"b01416d3.f69f38","name":"","url":"/update-sensor","method":"get","upload":false,"swaggerDoc":"","x":190,"y":460,"wires":[["60410cde.562a34"]]},{"id":"60410cde.562a34","type":"function","z":"b01416d3.f69f38","name":"","func":"msg.payload = msg.payload.temperature;\nreturn msg;","outputs":1,"noerr":0,"x":390,"y":460,"wires":[["e71c7a7d.e7c598","7f5cf345.63f56c"]]},{"id":"2b7ac01b.fc984","type":"ui_group","z":"","name":"SENSORS","tab":"99ab8dc5.f435c","disp":true,"width":"6","collapse":false},{"id":"99ab8dc5.f435c","type":"ui_tab","z":"","name":"HTTP","icon":"dashboard","order":1,"disabled":false,"hidden":false}]

 

다른 웹 서비스 또는 API

 

이 가이드에서 ESP32는 Node-RED에 HTTP 요청을 수행하지만, ThingSpeak, IFTTT.com(WebHooks 서비스), OpenWeatherMap.org, PHP 서버 등과 같은 다른 서비스와 함께 이러한 예제를 사용할 수 있습니다. 이 가이드에 제시된 모든 예제는 다른 API에서도 작동합니다.

 

요약하자면, 이 가이드를 모든 서비스와 호환되도록 하려면 서비스 API 문서를 검색해야 합니다. 그런 다음 서버 이름(URL 또는 IP 주소)과 요청에서 보낼 매개변수(URL 경로 또는 요청 본문)가 필요합니다. 마지막으로, 사용하려는 모든 API와 통합되도록 예제를 수정합니다.

 

1. ESP32 HTTP GET: URL의 값 또는 쿼리

 

첫 번째 예에서 ESP32는 서비스에서 판독값을 업데이트하기 위해 HTTP GET 요청을 합니다. 이 유형의 요청은 값을 필터링하거나, 값을 요청하거나, JSON 객체를 반환하는 데 사용될 수도 있습니다.

 

HTTP GET ESP32 Get Sensor Value Plain Text Status 200 OK

 

Arduino IDE로 ESP32 HTTP GET 코드 작성

 

필요한 보드 애드온과 라이브러리를 설치한 후 다음 코드를 Arduino IDE에 복사하지만 아직 업로드하지 마세요. 작동하도록 하려면 몇 가지 변경이 필요합니다.

 

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

//Your Domain name with URL path or IP address with path
String serverName = "http://192.168.1.106:1880/update-sensor";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200); 

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?temperature=24.37";
      
      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());
      
      // If you need Node-RED/server authentication, insert user and password below
      //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
      
      // Send HTTP GET request
      int httpResponseCode = http.GET();
      
      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

 

네트워크 자격 증명 설정

 

다음 줄을 네트워크 자격 증명으로 수정하세요: SSID와 비밀번호. 코드에는 변경해야 할 위치에 대한 주석이 잘 달려 있습니다.

 

// Replace with your network credentials
const char* ssid     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

 

serverName 설정

 

또한 ESP가 판독값을 자체 서버에 게시하도록 도메인 이름이나 Node-RED IP 주소를 입력해야 합니다.

 

String serverName = "http://192.168.1.106:1880/update-sensor";

 

이제 코드를 보드에 업로드하면 바로 작동합니다.

HTTP GET 요청을 만드는 방법을 알아보려면 다음 섹션을 읽어보세요.

 

HTTP GET 요청

 

loop()에서 샘플 데이터로 5초마다 HTTP GET 요청을 실제로 만듭니다.

 

String serverPath = serverName + "?temperature=24.37";

// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());

// If your need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

// Send HTTP GET request
int httpResponseCode = http.GET();

 

참고: Node-RED에서 인증이 필요한 경우 다음 줄의 주석 처리를 제거하고 Node-RED 사용자 이름과 비밀번호를 삽입합니다.

 

// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

 

// Node-RED/서버 인증이 필요한 경우 아래에 사용자 이름과 비밀번호를 삽입합니다.

//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

 

ESP32는 다음 URL에서 새 요청을 하여 센서 필드를 새 온도로 업데이트합니다.

 

http://192.168.1.106:1880/update-sensor?temperature=24.37

 

그런 다음 다음 코드 줄은 서버에서 HTTP 응답을 저장합니다.

 

if (httpResponseCode>0) {
  Serial.print("HTTP Response code: ");
  Serial.println(httpResponseCode);
  String payload = http.getString();
  Serial.println(payload);
}
else {
  Serial.print("Error code: ");
  Serial.println(httpResponseCode);
}

 

데모

 

보드에서 새 스케치를 실행하고 Node-RED 디버그 창을 엽니다. 샘플 값이 성공적으로 인쇄되는 것을 볼 수 있습니다(24.37).

 

 

2. ESP32 HTTP GET: JSON 데이터 객체 또는 일반 텍스트

 

다음 예제에서는 JSON 객체를 가져오고 ESP32로 디코딩하기 위한 HTTP GET 요청을 만드는 방법을 보여줍니다. 많은 API가 JSON 형식으로 데이터를 반환합니다.

 

HTTP GET ESP32 센서 JSON 데이터 가져오기

 

다음 스케치를 Arduino IDE에 복사합니다(SSID와 비밀번호를 입력합니다):

 

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>
#include <Arduino_JSON.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

//Your Domain name with URL path or IP address with path
const char* serverName = "http://192.168.1.106:1880/get-sensor";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

String sensorReadings;
float sensorReadingsArr[3];

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
              
      sensorReadings = httpGETRequest(serverName);
      Serial.println(sensorReadings);
      JSONVar myObject = JSON.parse(sensorReadings);
  
      // JSON.typeof(jsonVar) can be used to get the type of the var
      if (JSON.typeof(myObject) == "undefined") {
        Serial.println("Parsing input failed!");
        return;
      }
    
      Serial.print("JSON object = ");
      Serial.println(myObject);
    
      // myObject.keys() can be used to get an array of all the keys in the object
      JSONVar keys = myObject.keys();
    
      for (int i = 0; i < keys.length(); i++) {
        JSONVar value = myObject[keys[i]];
        Serial.print(keys[i]);
        Serial.print(" = ");
        Serial.println(value);
        sensorReadingsArr[i] = double(value);
      }
      Serial.print("1 = ");
      Serial.println(sensorReadingsArr[0]);
      Serial.print("2 = ");
      Serial.println(sensorReadingsArr[1]);
      Serial.print("3 = ");
      Serial.println(sensorReadingsArr[2]);
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;
    
  // Your Domain name with URL path or IP address with path
  http.begin(client, serverName);
  
  // If you need Node-RED/server authentication, insert user and password below
  //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  
  String payload = "{}"; 
  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

 

serverName 설정

 

도메인 이름이나 Node-RED IP 주소를 입력하면 ESP가 JSON 객체에서 검색할 센서 판독값을 요청합니다.

 

String serverName = "http://192.168.1.106:1880/get-sensor";

 

이제 코드를 보드에 업로드합니다.

 

HTTP GET 요청(JSON 객체)

 

loop()에서 httpGETRequest() 함수를 호출하여 HTTP GET 요청을 만듭니다.

 

sensorReadings = httpGETRequest(serverName);

 

httpGETRequest() 함수는 Node-RED 주소 http://192.168.1.106:1880/get-sensor에 요청을 하고 JSON 객체가 있는 문자열을 검색합니다.

 

String httpGETRequest(const char* serverName) {
  HTTPClient http;

  // Your IP address with path or Domain name with URL path 
  http.begin(serverName);

  // If you need Node-RED/server authentication, insert user and password below
  //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");


  // Send HTTP POST request
  int httpResponseCode = http.GET();

  String payload = "{}"; 

  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  // Free resources
  http.end();

  return payload;
}

 

참고: Node-RED에 인증이 필요한 경우 다음 줄의 주석 처리를 제거하고 Node-RED 사용자 이름과 비밀번호를 삽입합니다.

 

// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

 

 

JSON 객체 디코딩

 

값에 액세스하려면 JSON 객체를 디코딩하고 모든 값을 sensorReadingsArr 배열에 저장합니다.

 

JSONVar myObject = JSON.parse(sensorReadings);

// JSON.typeof(jsonVar) can be used to get the type of the var
if (JSON.typeof(myObject) == "undefined") {
  Serial.println("Parsing input failed!");
  return;
}

Serial.print("JSON object = ");
Serial.println(myObject);

// myObject.keys() can be used to get an array of all the keys in the object
JSONVar keys = myObject.keys();

for (int i = 0; i < keys.length(); i++) {
  JSONVar value = myObject[keys[i]];
  Serial.print(keys[i]);
  Serial.print(" = ");
  Serial.println(value);
  sensorReadingsArr[i] = double(value);
}
Serial.print("1 = ");
Serial.println(sensorReadingsArr[0]);
Serial.print("2 = ");
Serial.println(sensorReadingsArr[1]);
Serial.print("3 = ");
Serial.println(sensorReadingsArr[2]);

 

HTTP GET 데모

 

코드를 업로드한 후 Arduino IDE를 열면 다음 JSON 데이터를 수신하는 것을 볼 수 있습니다.

 

{"value1":24.25,"value2":49.54,"value3":1005.14}

 

그런 다음 Arduino IDE 직렬 모니터에 디코딩된 JSON 객체를 인쇄합니다.

 

 

디버깅 목적으로 요청된 정보는 Node-RED 디버그 창에도 인쇄됩니다.

 

 

3. ESP32 HTTP POST: URL 인코딩, JSON 데이터 객체, 일반 텍스트

 

마지막으로 ESP32로 HTTP POST 요청을 하는 방법을 알아봅니다.

 

이 예제를 사용하면 ESP32는 URL 인코딩, JSON 객체 또는 일반 텍스트의 세 가지 다른 유형의 본문 요청을 사용하여 HTTP POST 요청을 할 수 있습니다. 이것들은 가장 일반적인 방법이며 대부분의 API 또는 웹 서비스와 통합되어야 합니다.

 

HTTP POST ESP32 URL 인코딩 JSON 객체 데이터 일반 텍스트

 

다음 스케치를 Arduino IDE에 복사합니다(SSID와 비밀번호를 입력하세요):

 

/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

//Your Domain name with URL path or IP address with path
const char* serverName = "http://192.168.1.106:1880/update-sensor";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

void setup() {
  Serial.begin(115200);

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
 
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      WiFiClient client;
      HTTPClient http;
    
      // Your Domain name with URL path or IP address with path
      http.begin(client, serverName);
      
      // If you need Node-RED/server authentication, insert user and password below
      //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
      
      // Specify content-type header
      http.addHeader("Content-Type", "application/x-www-form-urlencoded");
      // Data to send with HTTP POST
      String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14";           
      // Send HTTP POST request
      int httpResponseCode = http.POST(httpRequestData);
      
      // If you need an HTTP request with a content type: application/json, use the following:
      //http.addHeader("Content-Type", "application/json");
      //int httpResponseCode = http.POST("{\"api_key\":\"tPmAT5Ab3j7F9\",\"sensor\":\"BME280\",\"value1\":\"24.25\",\"value2\":\"49.54\",\"value3\":\"1005.14\"}");

      // If you need an HTTP request with a content type: text/plain
      //http.addHeader("Content-Type", "text/plain");
      //int httpResponseCode = http.POST("Hello, World!");
     
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
        
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

 

serverName 설정

 

도메인 이름이나 Node-RED IP 주소를 입력하면 ESP가 샘플 센서 판독값을 게시합니다.

 

String serverName = "http://192.168.1.106:1880/update-sensor";

 

이제 코드를 보드에 업로드합니다.

 

HTTP POST URL 인코딩

 

URL 인코딩된 HTTP POST 요청을 만들려면 다음과 같이 하세요.

 

POST /update-sensor HTTP/1.1
Host: 192.168.1.106:1880
api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14
Content-Type: application/x-www-form-urlencoded

 

Arduino 코드에서 다음을 실행해야 합니다.

 

// Your Domain name with URL path or IP address with path
http.begin(serverName);

// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

// Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// Data to send with HTTP POST
String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14";

// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);

 

// URL 경로가 있는 도메인 이름 또는 경로가 있는 IP 주소

http.begin(serverName);

// Node-RED/서버 인증이 필요한 경우 아래에 사용자 이름과 비밀번호를 삽입합니다.

//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

// 콘텐츠 유형 헤더 지정

http.addHeader("Content-Type", "application/x-www-form-urlencoded");

// HTTP POST로 보낼 데이터

String httpRequestData = "api_key=tPmAT5Ab3j7F9&sensor=BME280&value1=24.25&value2=49.54&value3=1005.14";

// HTTP POST 요청 보내기

int httpResponseCode = http.POST(httpRequestData);

 

참고: Node-RED에 인증이 필요한 경우 다음 줄의 주석 처리를 제거하고 Node-RED 사용자 이름과 비밀번호를 삽입합니다.

 

// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

 

// Node-RED/서버 인증이 필요한 경우 아래에 사용자 및 비밀번호를 삽입합니다.

//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");

 

HTTP POST JSON 객체

 

또는 JSON 객체로 HTTP POST 요청을 하는 것을 선호하는 경우:

 

POST /update-sensor HTTP/1.1
Host: example.com
{api_key: "tPmAT5Ab3j7F9", sensor_name: "BME280", temperature: 24.25; humidity: 49.54; pressure: 1005.14}
Content-Type: application/json

 

다음 스니펫을 사용합니다.

 

http.addHeader("Content-Type", "application/json");

int httpResponseCode = http.POST("{\"api_key\":\"tPmAT5Ab3j7F9\",\"sensor\":\"BME280\",\"value1\":\"24.25\",\"value2\":\"49.54\",\"value3\":\"1005.14\"}");

 

 

HTTP 일반 텍스트

 

일반 텍스트나 값을 보내려면 다음을 사용하세요.

 

http.addHeader("Content-Type", "text/plain");

int httpResponseCode = http.POST("Hello, World!");

 

참고: 사용하는 Node-RED 흐름(웹 서비스)은 일반 텍스트를 수신하도록 설정되지 않았지만 통합하려는 API가 일반 텍스트나 값만 허용하는 경우 이전 스니펫을 사용할 수 있습니다.

 

HTTP POST 데모

 

Node-RED 디버그 창에서 ESP가 5초마다 HTTP POST 요청을 하는 것을 볼 수 있습니다.

 

 

이 예에서 해당 값은 3개의 게이지로 전송되고 Node-RED 대시보드에 표시됩니다.

 

http://raspberry-pi-ip-address:1880/ui

 

 

마무리

 

이 튜토리얼에서는 HTTP GET 및 HTTP POST 요청을 사용하여 ESP32를 온라인 서비스와 통합하는 방법을 알아보았습니다.

 

HTTP GET 및 HTTP POST는 대부분의 웹 서비스와 API에서 일반적으로 사용됩니다. 이러한 기능은 프로젝트에 유용할 수 있습니다. 센서 판독값을 IFTTT, ThingSpeak와 같은 웹 서비스에 게시하거나 ESP32 또는 Raspberry Pi 웹 서버 또는 자체 서버에 게시하거나 인터넷이나 데이터베이스에서 데이터를 요청하는 등의 작업을 할 수 있습니다.

 

ESP8266 보드를 사용하는 경우 ESP8266 NodeMCU HTTP GET 및 HTTP Post 요청 가이드를 읽어보세요.

 

다음도 읽어보시면 좋을 듯합니다.

 

  • [과정] Arduino IDE로 ESP32 배우기
  • PHP 스크립트를 사용하여 ESP32/ESP8266 이메일 알림 보내기
  • 차트를 사용하여 전 세계 어디에서나 센서 판독값 시각화(ESP32/ESP8266 + MySQL + PHP)
  • ESP32 릴레이 모듈 웹 서버
  • ESP32 및 ESP8266을 사용한 MicroPython 프로그래밍

 

이 프로젝트가 마음에 드셨으면 좋겠습니다. 궁금한 사항이 있으면 아래에 댓글을 남겨주시면 최대한 빨리 답변해드리겠습니다.

 

ESP32가 마음에 드셨다면 "Arduino IDE로 ESP32 배우기" 과정에 등록하는 것을 고려해 보세요. 여기에서 무료 ESP32 리소스에 액세스할 수도 있습니다.

 

읽어주셔서 감사합니다. 배움을 멈추지 마세요.

 

 

반응형

더욱 좋은 정보를 제공하겠습니다.~ ^^