본문 바로가기
JAVA

카카오톡 로그인 REST API, HttpClient 통해 이용해보기

by mingutistory 2020. 4. 10.
728x90
package com.spring.kakao;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.fasterxml.jackson.databind.JsonNode;

public class KakaoLogin {
	
	private static String client_id = "";
	private static String redirect_uri = "";
	
	public static String getAuthenticationUrl() {
		String url = "https://kauth.kakao.com/oauth/authorize?client_id="+client_id
				+ "&redirect_uri="+redirect_uri+"&response_type=code";
		return url; 
	}
	
	public static String getAccessToken(String code) {
        String requestURL = "https://kauth.kakao.com/oauth/token"; 
        List<NameValuePair> postParams = new ArrayList<NameValuePair>(); 
        
        postParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
        postParams.add(new BasicNameValuePair("client_id", client_id)); 
        postParams.add(new BasicNameValuePair("redirect_uri", redirect_uri)); 
        postParams.add(new BasicNameValuePair("code", code)); 
 
        HttpClient client = HttpClientBuilder.create().build(); 
        HttpPost post = new HttpPost(requestURL);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        
        String token = null; 
        
        try {
           UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams, "UTF-8"); 
           post.setEntity(entity); 
           HttpResponse response = client.execute(post); 
           
           if(response.getStatusLine().getStatusCode() == 200) {
        	   ResponseHandler<String> handler = new BasicResponseHandler();
        	   String body = handler.handleResponse(response);
        	   
        	   JSONParser parser = new JSONParser();
        	   Object obj = parser.parse(body);
        	   JSONObject jsonObj = (JSONObject) obj;
        	   
        	   token = (String) jsonObj.get("access_token");
           }
 
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
        return token;
    }
	
	public static int getMemberInfo(String token) {
		
		String requestURL = "https://kapi.kakao.com/v2/user/me"; 
        HttpClient client = HttpClientBuilder.create().build(); 
		HttpPost post = new HttpPost(requestURL);
		
        post.addHeader("Authorization", "Bearer " + token); 

        try {
            HttpResponse response = client.execute(post); 
            int responseCode = response.getStatusLine().getStatusCode(); 
            
            if(responseCode == 200) {
         	   
         	   ResponseHandler<String> handler = new BasicResponseHandler();
         	   String body = handler.handleResponse(response);
         	   
         	   JSONParser parser = new JSONParser();
         	   Object obj = parser.parse(body);
         	   JSONObject jsonObj = (JSONObject) obj;
         	   JSONObject properties = (JSONObject) jsonObj.get("properties"); 
         	   String nickname = (String) properties.get("nickname");        	  
         	   
         	   
            }else {
            	System.out.println("ERROR : " + responseCode);
            }
  
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         } catch (ClientProtocolException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		} catch (IOException e) {
 			// TODO Auto-generated catch block
 			e.printStackTrace();
 		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
         return 1;
     }
	

	
}

 카카오 로그인은 연동은 안해봐서 혼자 따로 다른 코드 혹은 블로그 최대한 참고 하지 않고

https://developers.kakao.com/docs/latest/ko/kakaologin/common

 

Kakao Developers

카카오 API를 활용하여 다양한 어플리케이션을 개발해보세요. 카카오 로그인, 메시지 보내기, 친구 API, 인공지능 API 등을 제공합니다.

developers.kakao.com

을 참고해서 구현해봤다.

 

우선 계속 302 에러가 났는데 그 경우에는 전부 다 경로 문제였다. 요청할 url을 제대로 확인 할 것. 

300x250

댓글