13주차_참고 : Requesthttp() 함수의 동작 상세설명 - dhryu60/SmartDevice_2025-1 GitHub Wiki
📌 함수 전체
void Requesthttp() {
if (client.connect(server, httpPort)) {
Serial.println("\nSuccessed connection, and request http protocol");
client.print(String("Get /B552584/ArpltnInforInqireSvc"));
client.print(String("/getMsrstnAcctoRltmMesureDnsty?serviceKey=") + apiKey);
client.print(String("&returnType=") + returnType);
client.print(String("&numOfRows=") + numOfRows);
client.print(String("&pageNo=") + pageNo);
client.print(String("&stationName=") + urlencode(stationName));
client.print(String("&dataTerm=") + dataTerm);
client.print(version);
client.print(" HTTP/1.1\r\n");
client.print("Host: " + String(server) + "\r\n");
client.print("Connection: close\r\n\r\n");
} else {
Serial.println("\nfailed connection");
}
}
🔍 1️⃣ 함수의 목적
- 공공데이터포털 API 서버(
apis.data.go.kr
)에 HTTP GET 요청을 보내 미세먼지 데이터를 요청한다. - Wi-Fi 연결 후 서버에 접속(
client.connect
)하고, GET 요청을 직접 문자열로 전송한다.
🔎 2️⃣ 각 코드 라인의 상세 설명
if (client.connect(server, httpPort))
🟢 client
는WiFiClient
객체.server
(즉, "apis.data.go.kr")의httpPort
(80번 포트)로 접속 시도.- 접속 성공 시 true 반환, 실패 시 false.
Serial.println("\nSuccessed connection, and request http protocol");
🟢 - 접속 성공 메시지를 시리얼 모니터에 출력.
client.print(String("Get /B552584/ArpltnInforInqireSvc"));
🟢 - HTTP GET 요청의 경로를 시작으로 전송.
/B552584/ArpltnInforInqireSvc
는 공공데이터포털의 미세먼지 API 경로.
client.print(String("/getMsrstnAcctoRltmMesureDnsty?serviceKey=") + apiKey);
🟢 - API 엔드포인트
getMsrstnAcctoRltmMesureDnsty
(측정소별 실시간 대기 측정정보)를 지정하고serviceKey
(인증키)를 추가.
client.print(String("&returnType=") + returnType);
🟢 - 응답 형식을 지정(
xml
또는json
).
client.print(String("&numOfRows=") + numOfRows);
🟢 - 요청 데이터의 행 수를 지정(여기선 1).
client.print(String("&pageNo=") + pageNo);
🟢 - 요청 페이지 번호 지정(1페이지).
client.print(String("&stationName=") + urlencode(stationName));
🟢 - 요청할 측정소 이름 지정("과천동").
urlencode()
로 URL 인코딩(한글 처리).
client.print(String("&dataTerm=") + dataTerm);
🟢 - 데이터 기간 선택(일간: "DAILY").
client.print(version);
🟢 - API 버전 추가(
&ver=1.3
).
client.print(" HTTP/1.1\r\n");
🟢 - HTTP 버전과 요청 끝에 줄바꿈 추가.
client.print("Host: " + String(server) + "\r\n");
🟢 - Host 헤더(요청 대상 서버)를 지정.
client.print("Connection: close\r\n\r\n");
🟢 - 요청 후 연결을 닫도록 지정(
Connection: close
). \r\n\r\n
은 HTTP 헤더의 끝을 의미.
else { Serial.println("\nfailed connection"); }
🟢 - 서버 접속 실패 시 메시지를 출력.
💡 3️⃣ 흐름 요약
1️⃣ Wi-Fi로 apis.data.go.kr
80포트에 접속 시도.
2️⃣ 성공 시, HTTP GET 요청을 문자열로 직접 작성하여 전송.
3️⃣ 요청에는 측정소 이름, 인증키 등 파라미터가 포함됨.
4️⃣ 요청 후 응답을 기다리고(루프에서 client.available()
처리)
5️⃣ 실패 시 접속 실패 메시지 출력.
🔎 4️⃣ 요청 예시 완성본 (결과적으로 보내는 HTTP 요청)
GET /B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty?serviceKey=...&returnType=xml&numOfRows=1&pageNo=1&stationName=%EA%B3%BC%EC%B2%9C%EB%8F%99&dataTerm=DAILY&ver=1.3 HTTP/1.1
Host: apis.data.go.kr
Connection: close