상세 컨텐츠

본문 제목

Java - 네이버 단축URL API

개발/Java

by 뉴에이스 2018. 10. 4. 09:28

본문

소스

 

public static void main(String[] args) {
	String clientId = "xxxxx"; // 애플리케이션 클라이언트 아이디값";
    String clientSecret = "xxxxx"; // 애플리케이션 클라이언트 시크릿값";
    try {
    	String orgUrl = URLEncoder.encode("https://news.naver.com/main/read.nhn?mode=LS2D&mid=shm&sid1=105&sid2=230&oid=277&aid=0004327179", "utf-8");
        String apiURL = "https://openapi.naver.com/v1/util/shorturl";
        URL url = new URL(apiURL);
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setRequestMethod("POST");
        con.setRequestProperty("X-Naver-Client-Id", clientId);
        con.setRequestProperty("X-Naver-Client-Secret", clientSecret);
        // post request
        String postParams = "url=" + orgUrl;
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(postParams);
        wr.flush();
        wr.close();
        int responseCode = con.getResponseCode();
        BufferedReader br;
        if(responseCode==200) { // 정상 호출
            br = new BufferedReader(new InputStreamReader(con.getInputStream()));
        } else {  // 에러 발생
            br = new BufferedReader(new InputStreamReader(con.getErrorStream()));
        }
        String inputLine;
        StringBuffer response = new StringBuffer();
        while ((inputLine = br.readLine()) != null) {
            response.append(inputLine);
        }
        br.close();
        System.out.println(response.toString());
    } catch (Exception e) {
        System.out.println(e);
    }
}

 

결과

 

{"message":"ok","result":{"hash":"G1vF5B18","url":"http://me2.do/G1vF5B18","orgUrl":"https://news.naver.com/main/read.nhn?mode=LS2D&mid=shm&sid1=105&sid2=230&oid=277&aid=0004327179"},"code":"200"}

관련글 더보기

댓글 영역