본문 바로가기
개발인생/Java Back-End

Naver Cloud Monitoring(Cloud Insight) API 사용법(2) - getServerInstanceList 가져오기

by DevOps_901126 2024. 5. 28.
반응형

1) Signature 생성하기 확인

 

Naver Cloud Monitoring(Cloud Insight) API 사용법(1) - Signature 생성하기

개발도구 : IntelliJ개발언어 : JAVA목표 : Naver Cloud Monitoring(Cloud Insight) API 를 사용하여 Access Key 와 Secret Key 로 Signature Key 를 생성한다.* Signature Key 는 API를 찌르기 위해서 Header 에 필요한 필수 Key 이다

jaeganism.tistory.com

 

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;

public class NcloudAPIGetServerInstanceList {


    public static void main(String[] args) {
        try {
            // 암호화 문자열 생성을 위한 기본값 설정
            String apicallMethod = "GET";
            String space = " ";
            String newLine = "\n";

            // Unix timestamp 설정
            String timestamp = String.valueOf(Instant.now().toEpochMilli());

            // Ncloud API Key 설정
            String ncloudAccessKey = "본인 Access Key 넣어야합니다";
            String ncloudSecretKey = "본인 Secret Key 넣어야합니다";

            // API URL 서버 정보
            String apiServer = "https://ncloud.apigw.ntruss.com";

            // API URI 서버 정보
            String apiUri = "/vserver/v2/getServerInstanceList?responseFormatType=json";

            // hmac으로 암호화할 문자열 생성
            String message = apicallMethod + space + apiUri + newLine + timestamp + newLine + ncloudAccessKey;

            // HMAC-SHA256 암호화
            String signingKey = createHmacSha256Signature(message, ncloudSecretKey);

            // HTTP 호출 헤더값 설정
            Map<String, String> httpHeader = new HashMap<>();
            httpHeader.put("x-ncp-apigw-timestamp", timestamp);
            httpHeader.put("x-ncp-iam-access-key", ncloudAccessKey);
            httpHeader.put("x-ncp-apigw-signature-v2", signingKey);

            System.out.println("httpHeader = " + httpHeader);

            // API 호출
            sendHttpRequest(apiServer + apiUri, httpHeader);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Signature 생성
    private static String createHmacSha256Signature(String message, String secretKey) throws NoSuchAlgorithmException, InvalidKeyException {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        hmacSha256.init(secretKeySpec);
        byte[] hash = hmacSha256.doFinal(message.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(hash);
    }

    // HTTP 요청
    private static void sendHttpRequest(String url, Map<String, String> headers) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .GET();

        System.out.println("requestBuilder = " + requestBuilder);

        for (Map.Entry<String, String> entry : headers.entrySet()) {
            requestBuilder.header(entry.getKey(), entry.getValue());
        }

        // request
        HttpRequest request = requestBuilder.build();
        System.out.println("request = " + request);

        // response
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println("response = " + response);

        // 응답 확인
        System.out.println("Response code: " + response.statusCode());
        System.out.println("Response body: " + response.body());
    }
}

 

 

설명은 주석에 다 되어있습니다 .감사합니다

반응형