네이버 클라우드 플랫폼 CDN+ Purge API 시작 가이드

개요

이 가이드에는 간단한 시나리오를 따라 CDN+ 인스턴스를 조회하고 Purge를 수행합니다.
자세한 문서는 네이버 클라우드 플랫폼 CDN+ Purge API reference를 참고하시기 바랍니다.

시나리오 수행

CDN 인스턴스별로 도메인 목록 조회

CDN 인스턴스 도메인 리스트 조회 API를 이용해서 cdnInstanceID와 Domain ID, cdn 설정정보를 확인합니다.

  • 액션
    • getCdnPlusInstanceList
  • 액션 파라미터
    • cdnInstanceNo : 인스턴스 번호 (선택)
구버전 (12월 Deprecated)

OAuth 외부 라이브러리를 이용하여 authorization 헤더에 authparams 포함하여 쉽게 요청할 수 있습니다.
자세한 사항은 Ncloud OAuth 인증 가이드를 참고하기 바랍니다.

signpost-core 라이브러리 : http://code.google.com/p/oauth-signpost/wiki/GettingStarted

  • consumerKey : 키 관리에서 볼 수 있는 accessKey
  • consumerSecret : 키 관리에서 볼 수 있는 secretKey
  • requstUrl : API 엔드포인트 URL
  • requestMethod : HTTP Request 메소드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;

public class OldSignClass {
    public static void main(String args[]) throws Exception {
        String consumerKey = $ConsumerAcessKey$;
        String consumerSecret = $ConsumerSecretKey$;
        String requestUrl = "https://api.ncloud.com/cdn/";
        String requestMethod = "GET";

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "getCdnPlusInstanceList");
        requestParameters.put("responseFormatType", "json");
        // requestParameters.put("cdnInstanceNo", $InstanceNo$);
        // InstanceNo는 선택 사항입니다.
        // 입력하면 해당 인스턴스만 조회하며, 입력하지 않으면 모든 인스턴스의 목록을 조회합니다.

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);

        URL url = new URL(requestUrl + queryString.toString());
        HttpURLConnection con = (HttpURLConnection)url.openConnection();

        con.setRequestMethod(requestMethod);
        con.setConnectTimeout(500000);
        con.setUseCaches(false);
        con.setDefaultUseCaches(false);

        consumer.sign(con);
        con.connect();

        int responseCode = con.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }
    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"getCdnPlusInstanceListResponse": {  "requestId": "7abe1213-969a-4fe4-bb39-371dc0dfad07",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 1,  "cdnPlusInstanceList": [    {      "cdnInstanceNo": "914893",      "cdnInstanceStatus": {        "code": "RUN",        "codeName": "CDN Plus Run State"      },      "cdnInstanceOperation": {        "code": "NULL",        "codeName": "CDN3 NULL OP"      },      "cdnInstanceStatusName": "running",      "createDate": "2018-08-30T16:25:43+0900",      "lastModifiedDate": "2018-08-30T16:36:00+0900",      "cdnInstanceDescription": "",      "serviceName": "test",      "isForLiveTranscoder": false,      "liveTranscoderInstanceNoList": [],      "isForImageOptimizer": false,      "imageOptimizerInstanceNo": "",      "isAvailablePartialDomainPurge": false,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "cdnPlusRule": {        "protocolTypeCode": "HTTP",        "serviceDomainTypeCode": "DEFAULT",        "originUrl": "bong.kr.objectstorage.ncloud.com",        "originPath": "",        "originHttpPort": 80,        "originHttpsPort": 0,        "forwardHostHeaderTypeCode": "ORIGIN_HOSTNAME",        "forwardHostHeader": "",        "cacheKeyHostNameTypeCode": "REQUEST_HOST_HEADER",        "isGzipCompressionUse": true,        "cachingOptionTypeCode": "CACHE_CONTROL_MAX_AGE",        "isErrorContentsResponseUse": false,        "cachingTtlTime": 604800,        "isQueryStringIgnoreUse": true,        "isRemoveVaryHeaderUse": true,        "isLargeFileOptimizationUse": false,        "gzipResponseTypeCode": "ORIGIN_RESPONSE",        "isReferrerDomainUse": false,        "referrerDomainList": [],        "isReferrerDomainRestrictUse": false,        "isSecureTokenUse": false,        "secureTokenPassword": "",        "isReissueSecureTokenPassword": false,        "certificateName": "",        "isAccessLogUse": false,        "accessLogFileStorageContainerName": ""      }    }  ]}}
신버전

새로운 API는, 인증 관련 헤더를 추가하는 과정을 거쳐 API를 호출하게 됩니다. 인증 관련 Signature를 만드는 방식은 v1, v2 두가지 방식이 있습니다.

v1 Signature

    public static String makeSignatureV1(String url, String apiKey, String accessKey, String secretKey, String timestamp, String method) throws Exception{
        String space = " ";
        String newLine = "\n";

        String message = new StringBuilder()
                .append(method)
                .append(space)
                .append(url)
                .append(newLine)
                .append(timestamp)
                .append(newLine)
                .append(apiKey)
                .append(newLine)
                .append(accessKey)
                .toString();

        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
        String encodeBase64String = Base64.encodeBase64String(rawHmac);

        return encodeBase64String;

    }

v2 Signature

    public static String makeSignatureV2(String url, String accessKey, String secretKey, String timestamp, String method) throws Exception{
        String space = " ";
        String newLine = "\n";

        String message = new StringBuilder()
                .append(method)
                .append(space)
                .append(url)
                .append(newLine)
                .append(timestamp)
                .append(newLine)
                .append(accessKey)
                .toString();

        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8"));
        String encodeBase64String = Base64.encodeBase64String(rawHmac);

        return encodeBase64String;

    }
  • url : Action 수행 URL (Query String 포함)
  • apiKey : API GateWay Access Key
  • accessKey : 유저 Access Key
  • secretKey : 유저 Secret Key
  • timestamp : Epoch 시간 (Milli 초)
  • method : HTTP Request 메소드

자세한 사항은 Ncloud APIs 공통 가이드를 참고하기 바랍니다.

  • 해당 코드는 Java 8 코드로 작성되었습니다. java.time.Instant 객체가 지원되지 않을 경우 TIMESTAMP 값을 밀리(mili)초 단위까지 생성하여야 합니다.

Java (v1)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class MainClass {

private final static String API_END_POINT = "https://ncloud.apigw.ntruss.com";
    private final static String getCdnPlusInstanceListURL = "/cdn/v1/getCdnPlusInstanceList";
    private final static String METHODS = "GET";

    private final static String API_GW_KEY = $ConsumerAPIGateWayKey$;
    private final static String ACCESS_KEY = $ConsumerAccessKey$;
    private final static String SECRET_KEY = $ConsumerSecretKey$;
    private final static String TIMESTAMP = Long.toString(Instant.now().toEpochMilli());


    public static void main(String args[]) throws Exception{

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "getCdnPlusInstanceList");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        String openURL = API_END_POINT + getCdnPlusInstanceListURL + queryString;
        URL obj = new URL(openURL);

        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("x-ncp-apigw-timestamp", TIMESTAMP);
        conn.setRequestProperty("x-ncp-apigw-api-key", API_GW_KEY);
        conn.setRequestProperty("x-ncp-iam-access-key", ACCESS_KEY);
        conn.setRequestProperty("x-ncp-apigw-signature-v1", makeSignatureV1(getCdnPlusInstanceListURL + queryString, API_GW_KEY, ACCESS_KEY, SECRET_KEY, TIMESTAMP, METHODS));
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        int responseCode = conn.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }

    }
}

main 메소드를 실행하면, 다음과 같은 결과를 얻을 수 있습니다.

{"getCdnPlusInstanceListResponse": {  "requestId": "107ea9fb-9442-486f-85d3-3d70777eac9e",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 1,  "cdnPlusInstanceList": [    {      "cdnInstanceNo": "914893",      "cdnInstanceStatus": {        "code": "RUN",        "codeName": "CDN Plus Run State"      },      "cdnInstanceOperation": {        "code": "NULL",        "codeName": "CDN3 NULL OP"      },      "cdnInstanceStatusName": "running",      "createDate": "2018-08-30T16:25:43+0900",      "lastModifiedDate": "2018-08-30T16:36:00+0900",      "cdnInstanceDescription": "",      "serviceName": "test",      "isForLiveTranscoder": false,      "liveTranscoderInstanceNoList": [],      "isForImageOptimizer": false,      "imageOptimizerInstanceNo": "",      "isAvailablePartialDomainPurge": false,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "cdnPlusRule": {        "protocolTypeCode": "HTTP",        "serviceDomainTypeCode": "DEFAULT",        "originUrl": "bong.kr.objectstorage.ncloud.com",        "originPath": "",        "originHttpPort": 80,        "originHttpsPort": 0,        "forwardHostHeaderTypeCode": "ORIGIN_HOSTNAME",        "forwardHostHeader": "",        "cacheKeyHostNameTypeCode": "REQUEST_HOST_HEADER",        "isGzipCompressionUse": true,        "cachingOptionTypeCode": "CACHE_CONTROL_MAX_AGE",        "isErrorContentsResponseUse": false,        "cachingTtlTime": 604800,        "isQueryStringIgnoreUse": true,        "isRemoveVaryHeaderUse": true,        "isLargeFileOptimizationUse": false,        "gzipResponseTypeCode": "ORIGIN_RESPONSE",        "isReferrerDomainUse": false,        "referrerDomainList": [],        "isReferrerDomainRestrictUse": false,        "isSecureTokenUse": false,        "secureTokenPassword": "",        "isReissueSecureTokenPassword": false,        "certificateName": "",        "isAccessLogUse": false,        "accessLogFileStorageContainerName": ""      }    }  ]}}

Java (v2)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class MainClass {
    private final static String API_END_POINT = "https://ncloud.apigw.ntruss.com";
    private final static String getCdnPlusInstanceListURL = "/cdn/v1/getCdnPlusInstanceList";
    private final static String METHODS = "GET";

    private final static String API_GW_KEY = $ConsumerAPIGateWayKey$;
    private final static String ACCESS_KEY = $ConsumerAccessKey$;
    private final static String SECRET_KEY = $ConsumerSecretKey$;
    private final static String TIMESTAMP = Long.toString(Instant.now().toEpochMilli());


    public static void main(String args[]) throws Exception{

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "getCdnPlusInstanceList");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        String openURL = API_END_POINT + getCdnPlusInstanceListURL + queryString;
        URL obj = new URL(openURL);

        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("x-ncp-apigw-timestamp", TIMESTAMP);
        conn.setRequestProperty("x-ncp-apigw-api-key", API_GW_KEY);
        conn.setRequestProperty("x-ncp-iam-access-key", ACCESS_KEY);
        conn.setRequestProperty("x-ncp-apigw-signature-v2", makeSignatureV2(getCdnPlusInstanceListURL + queryString, ACCESS_KEY, SECRET_KEY, TIMESTAMP, METHODS));
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        int responseCode = conn.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }

    }
}

main 메소드를 실행하면, 다음과 같은 결과를 얻을 수 있습니다.

{"getCdnPlusInstanceListResponse": {  "requestId": "8024ca8f-19f2-4025-b537-05b5582a1d46",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 1,  "cdnPlusInstanceList": [    {      "cdnInstanceNo": "914893",      "cdnInstanceStatus": {        "code": "RUN",        "codeName": "CDN Plus Run State"      },      "cdnInstanceOperation": {        "code": "NULL",        "codeName": "CDN3 NULL OP"      },      "cdnInstanceStatusName": "running",      "createDate": "2018-08-30T16:25:43+0900",      "lastModifiedDate": "2018-08-30T16:36:00+0900",      "cdnInstanceDescription": "",      "serviceName": "test",      "isForLiveTranscoder": false,      "liveTranscoderInstanceNoList": [],      "isForImageOptimizer": false,      "imageOptimizerInstanceNo": "",      "isAvailablePartialDomainPurge": false,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "cdnPlusRule": {        "protocolTypeCode": "HTTP",        "serviceDomainTypeCode": "DEFAULT",        "originUrl": "bong.kr.objectstorage.ncloud.com",        "originPath": "",        "originHttpPort": 80,        "originHttpsPort": 0,        "forwardHostHeaderTypeCode": "ORIGIN_HOSTNAME",        "forwardHostHeader": "",        "cacheKeyHostNameTypeCode": "REQUEST_HOST_HEADER",        "isGzipCompressionUse": true,        "cachingOptionTypeCode": "CACHE_CONTROL_MAX_AGE",        "isErrorContentsResponseUse": false,        "cachingTtlTime": 604800,        "isQueryStringIgnoreUse": true,        "isRemoveVaryHeaderUse": true,        "isLargeFileOptimizationUse": false,        "gzipResponseTypeCode": "ORIGIN_RESPONSE",        "isReferrerDomainUse": false,        "referrerDomainList": [],        "isReferrerDomainRestrictUse": false,        "isSecureTokenUse": false,        "secureTokenPassword": "",        "isReissueSecureTokenPassword": false,        "certificateName": "",        "isAccessLogUse": false,        "accessLogFileStorageContainerName": ""      }    }  ]}}

CDN Purge 수행

CDN 특정 도메인에 대하여 Purge를 수행합니다.

  • 액션
    • requestCdnPlusPurge
  • 액션 파라미터
    • cdnInstanceNo : 인스턴스 번호
    • isWholePurge : false (개별 파일 Purge 수행)
    • isWholeDomain
    • true : 도메인이 1개인 인스턴스로 전체 도메인 대상, 고객 보유 N개의 서비스 도메인 + Cache Key Hostname이 'ORIGIN_HOSTNAME'에 사용 => 전체 도메인 대상 Purge 수행
    • false : 고객 보유 N개의 서비스 도메인 + Cache Key Hostname이 'REQUEST_HOST_HEADER'에 사용 => 도메인 개별 Purge 수행
    • targetFileList.1 : /sample_img.jpg (Purge 대상 파일 경로와 파일명)
구버전 (12월 Deprecated)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;

public class OldSignClass {
    public static void main(String args[]) throws Exception {
        String consumerKey = $ConsumerAcessKey$;
        String consumerSecret = $ConsumerSecretKey$;
        String requestUrl = "https://api.ncloud.com/cdn/";
        String requestMethod = "GET";

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "requestCdnPlusPurge");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");
        requestParameters.put("isWholePurge", false);
        requestParameters.put("isWholeDomain", true);
        requestParameters.put("targetFileList.1", "/sample_img.jpeg");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);
        URL url = new URL(requestUrl + queryString.toString());
        HttpURLConnection con = (HttpURLConnection)url.openConnection();

        con.setRequestMethod(requestMethod);
        con.setConnectTimeout(500000);
        con.setUseCaches(false);
        con.setDefaultUseCaches(false);

        consumer.sign(con);
        con.connect();

        int responseCode = con.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }
    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"requestCdnPlusPurgeResponse": {  "requestId": "e1f78caa-32cd-4c7f-9afc-6d3fa48c4fcd",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 1,  "cdnPlusPurgeHistoryList": [    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005151",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-05T19:31:52+0900",      "purgeStatusName": "ready"    }  ]}}
신버전

Java (v1)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class MainClass {
    private final static String API_END_POINT = "https://ncloud.apigw.ntruss.com";
    private final static String requestCdnPlusPurge = "/cdn/v1/requestCdnPlusPurge";
    private final static String METHODS = "GET";

    private final static String API_GW_KEY = $ConsumerAPIGateWayKey$;
    private final static String ACCESS_KEY = $ConsumerAccessKey$;
    private final static String SECRET_KEY = $ConsumerSecretKey$;
    private final static String TIMESTAMP = Long.toString(Instant.now().toEpochMilli());


    public static void main(String args[]) throws Exception{

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "requestCdnPlusPurge");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");
        requestParameters.put("isWholePurge", false);
        requestParameters.put("isWholeDomain", true);
        requestParameters.put("targetFileList.1", "/sample_img.jpeg");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        String openURL = API_END_POINT + requestCdnPlusPurge + queryString;
        URL obj = new URL(openURL);

        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("x-ncp-apigw-timestamp", TIMESTAMP);
        conn.setRequestProperty("x-ncp-apigw-api-key", API_GW_KEY);
        conn.setRequestProperty("x-ncp-iam-access-key", ACCESS_KEY);
        conn.setRequestProperty("x-ncp-apigw-signature-v1", makeSignatureV1(requestCdnPlusPurge + queryString, API_GW_KEY, ACCESS_KEY, SECRET_KEY, TIMESTAMP, METHODS));
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        int responseCode = conn.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }

    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"requestCdnPlusPurgeResponse": {  "requestId": "fa3bb017-da9c-4b78-beb5-805a3a44ee6f",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 1,  "cdnPlusPurgeHistoryList": [    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005156",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:15:17+0900",      "purgeStatusName": "ready"    }  ]}}

Java (v2)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class MainClass {
    private final static String API_END_POINT = "https://ncloud.apigw.ntruss.com";
    private final static String requestCdnPlusPurge = "/cdn/v1/requestCdnPlusPurge";
    private final static String METHODS = "GET";

    private final static String API_GW_KEY = $ConsumerAPIGateWayKey$;
    private final static String ACCESS_KEY = $ConsumerAccessKey$;
    private final static String SECRET_KEY = $ConsumerSecretKey$;
    private final static String TIMESTAMP = Long.toString(Instant.now().toEpochMilli());


    public static void main(String args[]) throws Exception{

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "requestCdnPlusPurge");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");
        requestParameters.put("isWholePurge", false);
        requestParameters.put("isWholeDomain", true);
        requestParameters.put("targetFileList.1", "/sample_img.jpeg");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        String openURL = API_END_POINT + requestCdnPlusPurge + queryString;
        URL obj = new URL(openURL);

        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("x-ncp-apigw-timestamp", TIMESTAMP);
        conn.setRequestProperty("x-ncp-apigw-api-key", API_GW_KEY);
        conn.setRequestProperty("x-ncp-iam-access-key", ACCESS_KEY);
        conn.setRequestProperty("x-ncp-apigw-signature-v2", makeSignatureV2(requestCdnPlusPurge + queryString, ACCESS_KEY, SECRET_KEY, TIMESTAMP, METHODS));
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        int responseCode = conn.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }

    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"requestCdnPlusPurgeResponse": {  "requestId": "2424c83d-18e9-46b7-ba56-b8ae07e83c9a",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 1,  "cdnPlusPurgeHistoryList": [    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005157",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:17:41+0900",      "purgeStatusName": "ready"    }  ]}}

CDN Purge 이력 조회

CDN Purge를 수행한 기록을 조회합니다.

  • 액션
    • getCdnPlusPurgeHistoryList
  • 액션 파라미터
    • cdnInstanceNo : 인스턴스 번호
구버전 (12월 Deprecated)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.basic.DefaultOAuthConsumer;

public class OldSignClass {
    public static void main(String args[]) throws Exception {
        String consumerKey = $ConsumerAcessKey$;
        String consumerSecret = $ConsumerSecretKey$;
        String requestUrl = "https://api.ncloud.com/cdn/";
        String requestMethod = "GET";

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "getCdnPlusPurgeHistoryList");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret);
        URL url = new URL(requestUrl + queryString.toString());
        HttpURLConnection con = (HttpURLConnection)url.openConnection();

        con.setRequestMethod(requestMethod);
        con.setConnectTimeout(500000);
        con.setUseCaches(false);
        con.setDefaultUseCaches(false);

        consumer.sign(con);
        con.connect();

        int responseCode = con.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(con.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }
    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"getCdnPlusPurgeHistoryListResponse": {  "requestId": "bbf8e2d7-fc8b-4390-8968-ab1c2c341a73",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 3,  "cdnPlusPurgeHistoryList": [    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005157",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:17:41+0900",      "purgeStatusName": "success"    },    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005156",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:15:17+0900",      "purgeStatusName": "success"    },    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005151",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-05T19:31:52+0900",      "purgeStatusName": "success"    }  ]}}
신버전

Java (v1)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class MainClass {
    private final static String API_END_POINT = "https://ncloud.apigw.ntruss.com";
    private final static String getCdnPlusPurgeHistoryList = "/cdn/v1/getCdnPlusPurgeHistoryList";
    private final static String METHODS = "GET";

    private final static String API_GW_KEY = $ConsumerAPIGateWayKey$;
    private final static String ACCESS_KEY = $ConsumerAccessKey$;
    private final static String SECRET_KEY = $ConsumerSecretKey$;
    private final static String TIMESTAMP = Long.toString(Instant.now().toEpochMilli());


    public static void main(String args[]) throws Exception{

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "getCdnPlusPurgeHistoryList");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        String openURL = API_END_POINT + getCdnPlusPurgeHistoryList + queryString;
        URL obj = new URL(openURL);

        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("x-ncp-apigw-timestamp", TIMESTAMP);
        conn.setRequestProperty("x-ncp-apigw-api-key", API_GW_KEY);
        conn.setRequestProperty("x-ncp-iam-access-key", ACCESS_KEY);
        conn.setRequestProperty("x-ncp-apigw-signature-v1", makeSignatureV1(getCdnPlusPurgeHistoryList + queryString, API_GW_KEY, ACCESS_KEY, SECRET_KEY, TIMESTAMP, METHODS));
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        int responseCode = conn.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }

    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"getCdnPlusPurgeHistoryListResponse": {  "requestId": "358f1d4d-9811-4eb9-a4d5-364e9150cdf1",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 3,  "cdnPlusPurgeHistoryList": [    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005157",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:17:41+0900",      "purgeStatusName": "success"    },    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005156",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:15:17+0900",      "purgeStatusName": "success"    },    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005151",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-05T19:31:52+0900",      "purgeStatusName": "success"    }  ]}}

Java (v2)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class MainClass {
    private final static String API_END_POINT = "https://ncloud.apigw.ntruss.com";
    private final static String getCdnPlusPurgeHistoryList = "/cdn/v1/getCdnPlusPurgeHistoryList";
    private final static String METHODS = "GET";

    private final static String API_GW_KEY = $ConsumerAPIGateWayKey$;
    private final static String ACCESS_KEY = $ConsumerAccessKey$;
    private final static String SECRET_KEY = $ConsumerSecretKey$;
    private final static String TIMESTAMP = Long.toString(Instant.now().toEpochMilli());


    public static void main(String args[]) throws Exception{

        Map<String, Object> requestParameters = new HashMap<String, Object>();
        requestParameters.put("action", "getCdnPlusPurgeHistoryList");
        requestParameters.put("cdnInstanceNo", $InstanceNo$);
        requestParameters.put("responseFormatType", "json");

        StringBuffer queryString = new StringBuffer();
        int index= 1;
        int requestParamSize = requestParameters.size();
        for (String key : requestParameters.keySet()) {
            if (index == 1) {
                queryString.append("?");
            }
            queryString.append(key);

            if (requestParameters.get(key) != null) {
                queryString.append('=');
                queryString.append(URLEncoder.encode(requestParameters.get(key).toString(), "UTF-8"));
            }
            if (index!= requestParamSize) {
                queryString.append("&");
                index ++;
            }
        }

        String openURL = API_END_POINT + getCdnPlusPurgeHistoryList + queryString;
        URL obj = new URL(openURL);

        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("x-ncp-apigw-timestamp", TIMESTAMP);
        conn.setRequestProperty("x-ncp-apigw-api-key", API_GW_KEY);
        conn.setRequestProperty("x-ncp-iam-access-key", ACCESS_KEY);
        conn.setRequestProperty("x-ncp-apigw-signature-v2", makeSignatureV2(getCdnPlusPurgeHistoryList + queryString, ACCESS_KEY, SECRET_KEY, TIMESTAMP, METHODS));
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        int responseCode = conn.getResponseCode();
        System.out.println("ResponseCode : " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader resultReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            StringBuffer requestResult = new StringBuffer();
            String readString = null;
            while ((readString = resultReader.readLine()) != null) {
                requestResult.append(readString);
            }
            System.out.println(requestResult.toString());
        }

    }
}

main 메소드를 수행하면, 해당 결과를 얻을 수 있습니다.

{"getCdnPlusPurgeHistoryListResponse": {  "requestId": "1880f9ea-f96d-46bc-b4db-8e295a434f04",  "returnCode": "0",  "returnMessage": "success",  "totalRows": 3,  "cdnPlusPurgeHistoryList": [    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005157",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:17:41+0900",      "purgeStatusName": "success"    },    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005156",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-08T10:15:17+0900",      "purgeStatusName": "success"    },    {      "cdnInstanceNo": "914893",      "purgeId": "PT000000000000005151",      "isWholePurge": false,      "isWholeDomain": true,      "cdnPlusServiceDomainList": [        {          "domainId": "CD000000000000009748",          "serviceDomainTypeCode": "DEFAULT",          "protocolTypeCode": "HTTP",          "defaultDomainName": "rtvgyivztexc914893.cdn.ntruss.com",          "userDomainName": ""        }      ],      "targetDirectoryName": "",      "targetFileList": [        "/sample_img.jpeg"      ],      "requestDate": "2018-10-05T19:31:52+0900",      "purgeStatusName": "success"    }  ]}}

결과 수행 확인

아래 이미지와 같이 Purge를 수행했던 결과를 확인할 수 있습니다.

CDN에 URL을 요청하여 Cache 초기화와 콘텐츠 변경 사항을 확인합니다.

연관 정보 바로가기

아래 가이드에서 연관 정보를 확인할 수 있습니다.

""에 대한 건이 검색되었습니다.

    ""에 대한 검색 결과가 없습니다.

    처리중...