이번에는 토큰까지 한번에 받아오는 코드로!
package com.myspring.blog.kakao;
@Controller
@RequestMapping("/kakao")
public class kakaoController {
private Kakao_restapi kakao_restapi=new Kakao_restapi();
@RequestMapping(value="/oauth",method= RequestMethod.GET)
public String kakaoConnect() {
StringBuffer url = new StringBuffer();
url.append("https://kauth.kakao.com/oauth/authorize?");
url.append("client_id=" + "각자의 id~~");
url.append("&redirect_uri=http://localhost:8080/mytest04/kakao/callback");
url.append("&response_type=code");
return "redirect:" + url.toString();
}
@RequestMapping(value="/callback",produces="application/json",method= {RequestMethod.GET, RequestMethod.POST})
public String kakaoLogin(@RequestParam("code")String code,RedirectAttributes ra,HttpSession session,HttpServletResponse response )throws IOException {
System.out.println("kakao code:"+code);
JsonNode access_token=kakao_restapi.getKakaoAccessToken(code); -> 새로 추가된 코드임
System.out.println(access_token);
return "home";
}
}
새로 추가된 kakao_restapi 클래스
public class Kakao_restapi {
public static JsonNode getKakaoAccessToken(String code) { -> 여기서 코드 ~~
System.out.println("restapi클래스"+code);
final String RequestUrl = "https://kauth.kakao.com/oauth/token"; // Host
final List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("grant_type", "authorization_code"));
postParams.add(new BasicNameValuePair("client_id", "각자의 키로")); // REST API KEY
postParams.add(new BasicNameValuePair("redirect_uri", "http://localhost:8080/mytest04/kakao/callback")); // 리다이렉트 URI
postParams.add(new BasicNameValuePair("code", code)); // 로그인 과정중 얻은 code 값
final HttpClient client = HttpClientBuilder.create().build();
final HttpPost post = new HttpPost(RequestUrl);
JsonNode returnNode = null;
try {
post.setEntity(new UrlEncodedFormEntity(postParams));
final HttpResponse response = client.execute(post);
final int responseCode = response.getStatusLine().getStatusCode();
System.out.println("\nSending 'POST' request to URL : " + RequestUrl);
System.out.println("Post parameters : " + postParams);
System.out.println("Response Code : " + responseCode);
// JSON 형태 반환값 처리
ObjectMapper mapper = new ObjectMapper();
returnNode = mapper.readTree(response.getEntity().getContent());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return returnNode;
}
}
'API' 카테고리의 다른 글
spring 카카오 로그인 api 사용하기 3 (0) | 2019.03.08 |
---|---|
spring 카카오 로그인 api 사용하기 1 (0) | 2019.03.07 |