service 부분
private Logger logger = LoggerFactory.getLogger(KakaoService.class);
public String getAccessToken (String authorize_code) {
String access_Token = "";
String refresh_Token = "";
String reqURL = "https://kauth.kakao.com/oauth/token";
try {
URL url = new URL(reqURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// POST 요청을 위해 기본값이 false인 setDoOutput을 true로
conn.setRequestMethod("POST");
conn.setDoOutput(true);
// REST KEY - 752c7be03bf629c6299307d546d711d0
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()));
StringBuilder sb = new StringBuilder();
sb.append("grant_type=authorization_code");
sb.append("&client_id=752c7be03bf629c6299307d546d711d0");// Rest key
sb.append("&redirect_uri=http://localhost:9089/kakaoLogin");// 경로
sb.append("&code=" + authorize_code);
bw.write(sb.toString());
bw.flush();
// 결과 코드가 200이라면 성공
int responseCode = conn.getResponseCode();
logger.info(">>>> responseCode : " + responseCode);
// 요청을 통해 얻은 JSON타입의 Response 메세지 읽어오기
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line = "";
String result = "";
while ((line = br.readLine()) != null) {
result += line;
}
System.out.println("response body : " + result);
// Gson 라이브러리에 포함된 클래스로 JSON파싱 객체 생성
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(result);
access_Token = element.getAsJsonObject().get("access_token").getAsString();
refresh_Token = element.getAsJsonObject().get("refresh_token").getAsString();
System.out.println("access_token : " + access_Token);
System.out.println("refresh_token : " + refresh_Token);
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return access_Token;
}
controller 부분
// kakao login
@RequestMapping("/kakaoLogin")
public String home(@RequestParam(value = “code”, required = false) String code) throws Exception{
logger.info("######### code : " + code);
String access_Token = kakaoService.getAccessToken(code);
logger.info("###access_Token#### : " + access_Token);
return “redirect:/”;
}
콘솔 내용
/// 계속 400 오류가 뜨는데 뭐가 잘못됐는지 못찾겠습니다… 도움 부탁드려요