# 도로기상정보 (수집)

## 1️. 실시간도로환경 기상정보 수집 (PostRoadWeather)

### 요청 URL

```url
https://service.mqnicrnd5.com/api/v1/rw/collect/prw
```

### 연계 주기

10분&#x20;

### 프로토콜

HTTPS

### HTTP 메서드

POST

### 데이터 포맷

{% file src="<https://1360411665-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FFu56IUROVbsERWF6iOsE%2Fuploads%2FxsCJCJI4e3kA7SsfoKxF%2F%E1%84%83%E1%85%A9%E1%84%85%E1%85%A9%E1%84%80%E1%85%B5%E1%84%89%E1%85%A1%E1%86%BC%E1%84%8C%E1%85%A5%E1%86%BC%E1%84%87%E1%85%A9(%E1%84%89%E1%85%AE%E1%84%8C%E1%85%B5%E1%86%B8)_prw.pdf?alt=media&token=8c938e36-000e-4152-9d6d-59d5b6e913c9>" %}

### 참고사항

API를 요청할 때 다음 예와 같이 HTTP 요청 헤더에 접근 토큰(Access Token) 을 추가해야 합니다. <mark style="color:purple;">**접근 토큰 앞에 "Bearer " 문자열을 추가해야 한다는 점에 주의하세요.**</mark>

```
> POST /api/v1/rw/collect/prw
> Host: service.mqnicrnd5.com
> User-Agent: curl/7.64.1
> Accept: */*
> Authorization: Bearer <접근 토큰>
```

### 요청 예시

```sh
curl --location 'https://service.mqnicrnd5.com/api/v1/rw/collect/prw
--header 'Authorization: Bearer <접근 토큰>' \
--header 'Content-Type: application/json' \
--data '{
        "mecId": "RSU00001",
        "dttm": "20240703105500",
        "roadWeather": {
            "weatherData": {
                "ta": -3.1,
                "hm": 17.1,
                "pa": 1025.7,
                "ws": 10.1,
                "wd": 0.1,
                "cpsd": 0.0,
                "rn": 0.1,
                "statCd": "24"
            },
            "visibilityData": {
                "vs": 11.0,
                "at": -3.0,
                "statCd": "00"
            },
            "roadSurfaceData": {
                "ts": -3.1,
                "ft": -24.6,
                "wfh": 0.1,
                "ilt": 0.1,
                "sd": 0.3,
                "ip": 17.1,
                "st": 99,
                "f": 0.5,
                "statCd": "00"
            }
        }
}'
```

### 응답 파라미터

수집 API의 경우 별도 응답 파라미터가 아닌 HTTP Status Code로 성공 여부를 구분합니다.

<table data-full-width="false"><thead><tr><th align="center">Status Code</th><th align="center">설명</th></tr></thead><tbody><tr><td align="center">200</td><td align="center">성공</td></tr><tr><td align="center">400</td><td align="center">요청 파라미터 검증 실패</td></tr><tr><td align="center">401</td><td align="center">인증 실패</td></tr><tr><td align="center">500</td><td align="center">서버 오류</td></tr></tbody></table>

```json
{ 
  id: '7a02096f-5d6c-4057-8cc7-1f0b2e8eaaa1',
  status: 'OK',
  code: 200,
  header: 
   [ { key: 'Date', value: 'Tue, 26 Mar 2024 07:49:01 GMT' },
     { key: 'Content-Type', value: 'text/plain;charset=ISO-8859-1' },
     { key: 'Content-Length', value: '2' },
     { key: 'Connection', value: 'keep-alive' },
     { key: 'x-envoy-upstream-service-time', value: '15' },
     { key: 'server', value: 'istio-envoy' },
     { key: 'cache-control',
       value: 'no-cache, no-store, max-age=0, must-revalidate' },
     { key: 'pragma', value: 'no-cache' },
     { key: 'expires', value: '0' },
     { key: 'x-content-type-options', value: 'nosniff' },
     { key: 'x-frame-options', value: 'DENY' },
     { key: 'x-xss-protection', value: '0' },
     { key: 'referrer-policy', value: 'no-referrer' } ],
  stream: { type: 'Buffer', data: [ 79, 75 ] },
  cookie: [],
  responseTime: 26,
  responseSize: 2 
}
```

### 도로기상정보 수집 API 구현 예제

{% tabs %}
{% tab title="Java" %}

* json.jar (참고, Gradle, Maven 등 빌드 도구를 별도로 사용하시는 경우에는 불필요)
  * <https://search.maven.org/remotecontent?filepath=org/json/json/20250517/json-20250517.jar>

```java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.json.JSONObject; // JSON 라이브러리 추가 필요

public class weather_collect {

    public static void main(String[] args) {
        String accessToken = "Bearer  <접근토큰>" // 실제 접근 토큰으로 교체 필요

        // 현재 시간을 yyyyMMddHHmmss 형식으로 생성
        String currentDttm = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("mecId", "RSU00001");
        jsonObject.put("dttm", currentDttm);

        JSONObject roadWeather = new JSONObject();
        
        JSONObject weatherData = new JSONObject();
        weatherData.put("ta", -3.1);
        weatherData.put("hm", 17.1);
        weatherData.put("pa", 1025.7);
        weatherData.put("ws", 10.1);
        weatherData.put("wd", 0.1);
        weatherData.put("cpsd", 0);
        weatherData.put("rn", 0.1);
        weatherData.put("statCd", "24");
        
        JSONObject visibilityData = new JSONObject();
        visibilityData.put("vs", 11);
        visibilityData.put("at", -3);
        visibilityData.put("statCd", "00");
        
        JSONObject roadSurfaceData = new JSONObject();
        roadSurfaceData.put("ts", -3.1);
        roadSurfaceData.put("ft", -24.6);
        roadSurfaceData.put("wfh", 0.1);
        roadSurfaceData.put("ilt", 0.1);
        roadSurfaceData.put("sd", 0.3);
        roadSurfaceData.put("ip", 17.1);
        roadSurfaceData.put("st", 3);
        roadSurfaceData.put("f", 0.5);
        roadSurfaceData.put("statCd", "00");

        roadWeather.put("weatherData", weatherData);
        roadWeather.put("visibilityData", visibilityData);
        roadWeather.put("roadSurfaceData", roadSurfaceData);

        jsonObject.put("roadWeather", roadWeather);
        
        String apiURL = "https://service.mqnicrnd5.com/api/v1/rw/collect/prw"; 

        String responseBody = post(apiURL, jsonObject.toString(), accessToken);

        System.out.println("[currentDttm: "+ currentDttm + "] " + responseBody);
    }

    private static String post(String apiUrl, String jsonInputString, String accessToken) {
        HttpURLConnection con = connect(apiUrl);
        try {
            con.setRequestMethod("POST");
            con.setRequestProperty("Authorization", accessToken);
            con.setRequestProperty("Content-Type", "application/json; utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setDoOutput(true);

            try(OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);           
            }

            int responseCode = con.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) { // 정상 호출
                return readBody(con.getInputStream());
            } else { // 오류 발생
                return readBody(con.getErrorStream());
            }
        } catch (IOException e) {
            throw new RuntimeException("API 호출 중 오류 발생: ", e);
        } finally {
            con.disconnect();
        }
    }


    private static HttpURLConnection connect(String apiUrl) {
        try {
            URL url = new URL(apiUrl);
            return (HttpURLConnection) url.openConnection();
        } catch (MalformedURLException e) {
            throw new RuntimeException("API URL이 잘못되었습니다. : " + apiUrl, e);
        } catch (IOException e) {
            throw new RuntimeException("연결이 실패했습니다. : " + apiUrl, e);
        }
    }


    private static String readBody(InputStream body) {
        InputStreamReader streamReader = new InputStreamReader(body);


        try (BufferedReader lineReader = new BufferedReader(streamReader)) {
            StringBuilder responseBody = new StringBuilder();


            String line;
            while ((line = lineReader.readLine()) != null) {
                responseBody.append(line);
            }


            return responseBody.toString();
        } catch (IOException e) {
            throw new RuntimeException("API 응답을 읽는 데 실패했습니다.", e);
        }
    }
}
```

{% endtab %}

{% tab title="Python" %}

```python
import requests
import json
from datetime import datetime

def call_api():
    access_token = "Bearer <접근토큰>"  # 실제 접근 토큰으로 교체 필요

    # 현재 시간을 yyyyMMddHHmmss 형식으로 생성
    current_dttm = datetime.now().strftime("%Y%m%d%H%M%S")

    # 데이터 구조 생성
    data = {
        "mecId": "RSU00001",
        "dttm": current_dttm,
        "roadWeather": {
            "weatherData": {
                "ta": -3.1,
                "hm": 17.1,
                "pa": 1025.7,
                "ws": 10.1,
                "wd": 0.1,
                "cpsd": 0,
                "rn": 0.1,
                "statCd": "24"
            },
            "visibilityData": {
                "vs": 11,
                "at": -3,
                "statCd": "00"
            },
            "roadSurfaceData": {
                "ts": -3.1,
                "ft": -24.6,
                "wfh": 0.1,
                "ilt": 0.1,
                "sd": 0.3,
                "ip": 17.1,
                "st": 3,
                "f": 0.5,
                "statCd": "00"
            }
        }
    }

    api_url = "https://service.mqnicrnd5.com/api/v1/rw/collect/prw"
    headers = {
        "Authorization": access_token,
        "Content-Type": "application/json",
        "Accept": "application/json"
    }

    response = requests.post(api_url, headers=headers, data=json.dumps(data))

    if response.status_code == 200:
        return f"[currentDttm: {current_dttm}] {response.text}"
    else:
        return f"[currentDttm: {current_dttm}] Error: {response.status_code}, Message: {response.text}"

if __name__ == "__main__":
    print(call_api())
```

{% endtab %}

{% tab title="Node.js" %}

```javascript
const https = require('https');

function main() {
    const accessToken = 'Bearer <접근토큰>';

    // 현재 시간을 yyyyMMddHHmmss 형식으로 생성
    const now = new Date();
    const currentDttm = now.getFullYear().toString() +
        (now.getMonth() + 1).toString().padStart(2, '0') +
        now.getDate().toString().padStart(2, '0') +
        now.getHours().toString().padStart(2, '0') +
        now.getMinutes().toString().padStart(2, '0') +
        now.getSeconds().toString().padStart(2, '0');

    const data = {
        "mecId": "RSU00001",
        "dttm": currentDttm,
        "roadWeather": {
            "weatherData": {
                "ta": -3.1,
                "hm": 17.1,
                "pa": 1025.7,
                "ws": 10.1,
                "wd": 0.1,
                "cpsd": 0,
                "rn": 0.1,
                "statCd": "24"
            },
            "visibilityData": {
                "vs": 11,
                "at": -3,
                "statCd": "00"
            },
            "roadSurfaceData": {
                "ts": -3.1,
                "ft": -24.6,
                "wfh": 0.1,
                "ilt": 0.1,
                "sd": 0.3,
                "ip": 17.1,
                "st": 3,
                "f": 0.5,
                "statCd": "00"
            }
        }
    };

    const apiURL = 'https://service.mqnicrnd5.com/api/v1/rw/collect/prw';
    const headers = {
        'Authorization': accessToken,
        'Content-Type': 'application/json'
    };

    post(apiURL, headers, data)
        .then(responseBody => {
            console.log(`[currentDttm: ${currentDttm}] ${responseBody}`);
        })
        .catch(error => {
            console.error(`[currentDttm: ${currentDttm}] Error:`, error);
        });
}

function post(apiURL, headers, data) {
    return new Promise((resolve, reject) => {
        const jsonData = JSON.stringify(data);
        
        const url = new URL(apiURL);
        const options = {
            hostname: url.hostname,
            port: url.port || 443,
            path: url.pathname,
            method: 'POST',
            headers: {
                ...headers,
                'Content-Length': Buffer.byteLength(jsonData)
            }
        };

        const req = https.request(options, response => {
            let responseData = '';
            
            response.on('data', chunk => {
                responseData += chunk;
            });

            response.on('end', () => {
                resolve(responseData);
            });
        });

        req.on('error', error => {
            reject(error);
        });

        req.write(jsonData);
        req.end();
    });
}

main();

```

{% endtab %}

{% tab title="C#" %}
준비 중 입니다.
{% endtab %}
{% endtabs %}
