언어/자바

API 연동(1)_ 토큰발급

토킹포테토 2022. 10. 21. 16:27
728x90

 


1. API(Application Programming interface) 란?

: 응용 프로그램에서 사용할 수 있도록, 운영 체제나 프로그래밍 언어가 제공하는 기능을 제어할 수 있게 만든 인터페이스를 뜻한다

즉, 어떤 방식으로 정보를 요청해야하는지, 이러한 요청 시 어떠한 형식으로 데이터를 전달 받을 수 있을지에 대해 정리한 일종의 규격이라고 볼 수 있다.


* 토큰 요청 

 

명세서

URL, HTTP 요청/응답 Header와 Body(JSON)로 구성되어 있다.
HTTP Header 『Content-Type』은 요청/응답: 『application/json; charset=UTF-8』로 한다.

 

요청 메시지

HTTP 항목명 필수 타입 설명(비고)
BODY id Y String(50) 발급받은 ID
pw Y String(50) 발급받은 PW

응답 메시지

HTTP 항목명 필수 타입 설명(비고)
BODY token_type Y String(10) 접근 토큰 유형
access_token Y String(800) 발급 된 접근토큰

 

public String getToken() throws IOException {

URL url = new URL("토큰을 요청할 url");

    String id="아이디";
    String pw = "비밀번호";
    String token="";

    BufferedWriter bw = null;
    BufferedReader in = null;

    try{
   		//토큰 요청
        HttpURLConnection con = (HttpURLConnection) url.openConnection();

        con.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
        con.setRequestProperty("Accept", " application/json");
        con.setDoOutput(true);

         JSONObject body = new JSONObject();
         body.put("id", id);
         body.put("pw", pw);			 

         bw = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
         bw.write(body.toString());
         bw.flush();

        //요청에 대한 응답값 받기
        in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String inputLine;
        String result = "";

        while( (inputLine = in.readLine()) != null ){
        result += inputLine;
        }

        System.out.println("GET TOKEN - RESPONSE BODY : " + result);

        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(result);

        token = elemnet.getAsJsonObject().get("access_token").getAsString();
        
        }catch(Exception e) {
            e.printStackTrace();
        }finally{
            if(bw != null) bw.close();
            if(in != null) in.close();
        }
    return token;
}​

 

'언어 > 자바' 카테고리의 다른 글

[JAVA IO]FileInputStream & FileOutputStream  (0) 2023.03.09
쿠키(Cookie)와 세션(Session)  (0) 2022.11.22
AES256 암호화, 복호화  (0) 2022.10.25
자바 특수 문자, 정규식 처리  (0) 2022.10.24
JSON 이란?  (0) 2022.10.24