카테고리 없음

Arduino -HTTP Request

기하 2021. 8. 16. 07:27

Arduino - HTTP 요청

 

Arduino는 웹 서버에 HTTP를 만드는 웹 클라이언트 역할을 할 수 있습니다. 

웹 서버는 웹사이트, 웹 API 또는 REST API, 웹 서비스 등일 수 있습니다.

이 튜토리얼에서는 다음을 배울 것입니다.

  • 웹 클라이언트 및 웹 서버에 대한 기본 지식
  • HTTP 요청(GET 및 POST)을 만드는 방법
  • 웹 서버에 데이터를 보내는 방법(웹사이트, WEB API 또는 REST API)
  • 아두이노 코드:

다른 WiFi 또는 이더넷 쉴드/보드의 코드도 비슷합니다. 차이점은 라이브러리에만 있습니다.

 

필요한 하드웨어

Arduino UNO 또는 Genuino UNO
USB 2.0 케이블 유형 A/B
아두이노 이더넷 쉴드 2
이더넷 케이블

또는

Arduino UNO 또는 Genuino UNO
USB 2.0 케이블 유형 A/B
PHPoC WiFi/이더넷 쉴드
(옵션)이더넷 케이블

 

웹 클라이언트 및 웹 서버에 대한 기본 지식

PC나 스마트폰에서 웹사이트에 접속할 때 웹 브라우저에 웹 주소(URL)를 입력하고

잠시 기다리면 해당 웹페이지가 PC/스마트폰에 표시됩니다. 

당신은 당신의 PC/스마트폰이 화면 뒤에서 무엇을 하는지 모릅니다. 

그래서 화면 뒤에서 어떤 일이 발생합니까?

  1. PC/스마트폰(웹 클라이언트)이 웹 서버에 HTTP 요청을 합니다.
  2. 웹 서버는 PC/스마트폰에 HTTP 응답을 반환합니다.
  3. PC/스마트폰은 HTTP 응답을 수신하고 화면에 HTTP 응답을 시각화합니다.

이 튜토리얼에서는 Arduino를 웹 클라이언트로 만들어 PC/스마트폰과 유사한 작업을 수행합니다.

 

웹 주소(URL)

URL에는 두 부분이 포함되어 있습니다 호스트이름  경로이름  . 

호스트 이름은 웹 서버의 IP 주소로 대체될 수 있습니다. 예: example.com /test

 

HTTP GET 요청에서 URL은 쿼리 문자열 포함할 수 있습니다 . 

예: example.com /test ?temperature=20&humidity=70 .

쿼리 문자열

쿼리 문자열은 웹 클라이언트에서 웹 서버로 데이터를 보내기 위한

HTTP 요청에 포함된  name-value 쌍의 집합입니다.

name과 value은 "=" 문자로 구분됩니다. name-value 쌍은 "&" 문자로 구분됩니다.

예: temperature=26&humidity=70&state=2

HTTP Request

HTTP request은 다음으로 구성됩니다

  • HTTP request header
  • HTTP  request body (선택 사항) 

HTTP 요청 헤더와 HTTP 요청 본문은두 쌍의

캐리지 리턴 문자(ASCII 13 또는 '\r')와 개행 문자(ASCII 10 또는 '\r')로 구분됩니다.

 

많은 요청 방법이 있습니다. 

그 중 GET과 POST의 두 가지 인기 있는 방법이 있습니다.

 

일반적으로 웹 서버에서 데이터를 가져오려면 GET 방식을 사용하고

웹 서버로 데이터를 보낼 때는 POST 방식을 사용합니다. 

그러나 GET 메서드는 웹 서버에서 데이터를 가져오고 보내는 데 사용할 수 있습니다.

전제 조건

다음 값을 결정해야 합니다.

  • 웹 주소    (URL)
  • 요청 방법 (POST 또는 GET)
  • 웹 서버가 사용하는 HTTP 포트(대부분의 웹 서버는 HTTP에 포트 80을 사용함)
  • (선택 사항) 웹 서버로 보낼 데이터( 쿼리 문자열 ). 
    이 튜토리얼에서는 ?temperature={t-value}&humidity={h-value} 형식으로
    온도와 습도를 웹 서버에 보낸다고 가정합니다 .

웹 주소(URL)는 호스트 이름  경로 이름 으로 분할됩니다.

HTTP Request을 만드는 방법

이 부분은 HTTP와 관련된 코드만을 제시합니다. 전체 코드는 마지막 부분에 표시됩니다.

  • 요청 방법, HTTP 포트, 호스트 이름 , 경로 이름 , 쿼리 문자열 등을 선언
    int    HTTP_PORT   = 80;
    String HTTP_METHOD = "GET"; // or "POST"
    char   HOST_NAME[] = "example.phpoc.com"; // hostname of web server:
    String PATH_NAME   = "";
  • web client 객체를 선언
    //Arduino Ethernet Shield 2 
    EthernetClient client;
    
    //PHPoC WiFi/Ethernet Shield
    PhpocClient client;
    
    //Arduino Uno WiFi 
    WiFiClient client;
  • 웹 서버에 연결합니다
    if(client.connect(HOST_NAME, HTTP_PORT)) {
      Serial.println("Connected to server");
    } else {
      Serial.println("connection failed");
    }​
  • 웹서버에 접속되면 HTTP request를 보낸다.
    // send HTTP request header
    client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP request header​
  • 웹서버로 부터 response data 를 읽는다.
    while(client.available())
    {
      // read an incoming byte from the server and print them to serial monitor:
      char c = client.read();
      Serial.print(c);
    }
    
    if(!client.connected())
    {
      // if the server's disconnected, stop the client:
      Serial.println("disconnected");
      client.stop();
    }​

웹 서버에 데이터를 보내는 방법

HTTP request에 데이터를 포함할 수 있습니다. 데이터 형식은 HTTP 요청 방법에 따라 다릅니다.

  • HTTP GET 요청
    - 쿼리 스트링에 data만  보내면 된다.
    - Data는 경로이름에 붙이면 된다.
  • HTTP POST 요청
    -
    쿼리 스트링 포맷 뿐아니라 Json, XML, image등 다른 포맷으로도 보낼 수 있다.
    - Data는 HTTP Request body

HTTP 요청을 보내기 위한 코드를 수정하기만 하면 됩니다.

  • 쿼리 문자열 빌드
    int temp = // read from sensor
    int humi = // read from sensor
    String queryString = String("?temperature=") + String(temp) + String("&humidity=") + String(humi);​
  • HTTP 요청에서 데이터 전송을 위한 코드 수정
    - HTTP GET: append query string to pathname
    // send HTTP header
    client.println("GET " + PATH_NAME + queryString + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header​

    - HTTP POST: send query string as HTTP body
    // send HTTP header
    client.println("POST " + PATH_NAME + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header
    
    // send HTTP body
    client.println(queryString);​
  • 웹 서버에서 응답 데이터 읽기
    while(client.available())
    {
      // read an incoming byte from the server and print them to serial monitor:
      char c = client.read();
      Serial.print(c);
    }
    
    if(!client.connected())
    {
      // if the server's disconnected, stop the client:
      Serial.println("disconnected");
      client.stop();
    }

HTTP 요청을 위한 완전한 Arduino 코드

 HTTP GET/POST 요청을 만들기 위한 완전한 arduino 코드입니다.

Arduino Ethernet Shield 2를 사용한 Arduino HTTP GET/POST 요청

/*
 * Created by ArduinoGetStarted.com
 *
 * This example code is in the public domain
 *
 * Tutorial page: https://arduinogetstarted.com/tutorials/arduino-http-request
 */

#include <SPI.h>
#include <Ethernet.h>

// replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetClient client;

int    HTTP_PORT   = 80;
String HTTP_METHOD = "GET"; // or POST
char   HOST_NAME[] = "maker.ifttt.com";
String PATH_NAME   = "/trigger";

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

  // initialize the Ethernet shield using DHCP:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to obtaining an IP address using DHCP");
    while(true);
  }

  // connect to web server on port 80:
  if(client.connect(HOST_NAME, HTTP_PORT)) {
    // if connected:
    Serial.println("Connected to server");
    // make a HTTP request:
    // send HTTP header
    client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header

    while(client.connected()) {
      if(client.available()){
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    // the server's disconnected, stop the client:
    client.stop();
    Serial.println();
    Serial.println("disconnected");
  } else {// if not connected:
    Serial.println("connection failed");
  }
}

void loop() {

}

 

PHPoC Shields를 사용한 Arduino HTTP GET/POST 요청

/*
 * Created by ArduinoGetStarted.com
 *
 * This example code is in the public domain
 *
 * Tutorial page: https://arduinogetstarted.com/tutorials/arduino-http-request
 */

#include <Phpoc.h>

PhpocClient client;

int    HTTP_PORT   = 80;
String HTTP_METHOD = "GET"; // or POST
char   HOST_NAME[] = "maker.ifttt.com";
String PATH_NAME   = "/trigger/button-press/with/key/xxxxx";

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

  // initialize PHPoC [WiFi] Shield:
  Phpoc.begin();

  // connect to web server on port 80:
  if(client.connect(HOST_NAME, HTTP_PORT)) {
    // if connected:
    Serial.println("Connected to server");
    // make a HTTP request:
    // send HTTP header
	client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header

    while(client.connected()) {
      if(client.available()){
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    // the server's disconnected, stop the client:
    client.stop();
    Serial.println();
    Serial.println("disconnected");
  } else {// if not connected:
    Serial.println("connection failed");
  }
}

void loop() {

}

 

데이터로 HTTP GET 요청을 만들기 위한 완전한 Arduino 코드

Arduino Ethernet Shield 2를 사용하여 데이터가 포함된 Arduino HTTP GET 요청

/*
 * Created by ArduinoGetStarted.com
 *
 * This example code is in the public domain
 *
 * Tutorial page: https://arduinogetstarted.com/tutorials/arduino-http-request
 */

#include <SPI.h>
#include <Ethernet.h>

// replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetClient client;

int    HTTP_PORT   = 80;
String HTTP_METHOD = "GET";
char   HOST_NAME[] = "maker.ifttt.com";
String PATH_NAME   = "/trigger";
String queryString = "?value1=26&value2=70";;

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

  // initialize the Ethernet shield using DHCP:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to obtaining an IP address using DHCP");
    while(true);
  }

  // connect to web server on port 80:
  if(client.connect(HOST_NAME, HTTP_PORT)) {
    // if connected:
    Serial.println("Connected to server");
    // make a HTTP request:
    // send HTTP header
    client.println(HTTP_METHOD + " " + PATH_NAME + queryString + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header

    while(client.connected()) {
      if(client.available()){
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    // the server's disconnected, stop the client:
    client.stop();
    Serial.println();
    Serial.println("disconnected");
  } else {// if not connected:
    Serial.println("connection failed");
  }
}

void loop() {

}

 

PHPoC Shields를 사용하여 데이터가 포함된 Arduino HTTP GET 요청

/*
 * Created by ArduinoGetStarted.com
 *
 * This example code is in the public domain
 *
 * Tutorial page: https://arduinogetstarted.com/tutorials/arduino-http-request
 */

#include <SPI.h>
#include <Ethernet.h>

// replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetClient client;

int    HTTP_PORT   = 80;
String HTTP_METHOD = "GET";
char   HOST_NAME[] = "maker.ifttt.com";
String PATH_NAME   = "/trigger";
String queryString = "?value1=26&value2=70";;

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

  // initialize the Ethernet shield using DHCP:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to obtaining an IP address using DHCP");
    while(true);
  }

  // connect to web server on port 80:
  if(client.connect(HOST_NAME, HTTP_PORT)) {
    // if connected:
    Serial.println("Connected to server");
    // make a HTTP request:
    // send HTTP header
    client.println(HTTP_METHOD + " " + PATH_NAME + queryString + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header

    while(client.connected()) {
      if(client.available()){
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    // the server's disconnected, stop the client:
    client.stop();
    Serial.println();
    Serial.println("disconnected");
  } else {// if not connected:
    Serial.println("connection failed");
  }
}

void loop() {

}

 

데이터로 HTTP POST 요청을 만들기 위한 완전한 Arduino 코드

Arduino Ethernet Shield 2를 사용하여 데이터가 포함된
Arduino HTTP POST 요청

/*
 * Created by ArduinoGetStarted.com
 *
 * This example code is in the public domain
 *
 * Tutorial page: https://arduinogetstarted.com/tutorials/arduino-http-request
 */

#include <SPI.h>
#include <Ethernet.h>

// replace the MAC address below by the MAC address printed on a sticker on the Arduino Shield 2
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

EthernetClient client;

int    HTTP_PORT   = 80;
String HTTP_METHOD = "POST";
char   HOST_NAME[] = "maker.ifttt.com";
String PATH_NAME   = "/trigger";
String queryString = "?value1=26&value2=70";;

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

  // initialize the Ethernet shield using DHCP:
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to obtaining an IP address using DHCP");
    while(true);
  }

  // connect to web server on port 80:
  if(client.connect(HOST_NAME, HTTP_PORT)) {
    // if connected:
    Serial.println("Connected to server");
    // make a HTTP request:
    // send HTTP header
    client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header

    // send HTTP body
    client.println(queryString);

    while(client.connected()) {
      if(client.available()){
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    // the server's disconnected, stop the client:
    client.stop();
    Serial.println();
    Serial.println("disconnected");
  } else {// if not connected:
    Serial.println("connection failed");
  }
}

void loop() {

}

 

PHPoC Shields를 사용하여 데이터가 포함된 Arduino HTTP POST 요청

/*
 * Created by ArduinoGetStarted.com
 *
 * This example code is in the public domain
 *
 * Tutorial page: https://arduinogetstarted.com/tutorials/arduino-http-request
 */

#include <Phpoc.h>

PhpocClient client;

int    HTTP_PORT   = 80;
String HTTP_METHOD = "POST";
char   HOST_NAME[] = "maker.ifttt.com";
String PATH_NAME   = "/trigger/button-press/with/key/xxxxx";
String queryString = "?value1=26&value2=70";;

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

  // initialize PHPoC [WiFi] Shield:
  Phpoc.begin();

  // connect to web server on port 80:
  if(client.connect(HOST_NAME, HTTP_PORT)) {
    // if connected:
    Serial.println("Connected to server");
    // make a HTTP request:
    // send HTTP header
    client.println(HTTP_METHOD + " " + PATH_NAME + " HTTP/1.1");
    client.println("Host: " + String(HOST_NAME));
    client.println("Connection: close");
    client.println(); // end HTTP header

    // send HTTP body
    client.println(queryString);

    while(client.connected()) {
      if(client.available()){
        // read an incoming byte from the server and print it to serial monitor:
        char c = client.read();
        Serial.print(c);
      }
    }

    // the server's disconnected, stop the client:
    client.stop();
    Serial.println();
    Serial.println("disconnected");
  } else {// if not connected:
    Serial.println("connection failed");
  }
}

void loop() {

}

 

※ 참고:

이 자습서에서는 DHCP를 통해 동적 IP 주소를 사용했습니다. 고정 IP 주소를 사용하려는 경우:

[참조 번역공유] https://arduinogetstarted.com/tutorials/arduino-http-request