사용자 정보 요청하는 방법
사용자 정보를 요청하면 아래의 정보들을 응답해주는데 회원번호와 카카오계정이 중요하다.
카카오계정 정보에는 프로필, 이메일, 연령대, 생일 등등 이 있으나 나는 프로필, 이메일 외에는 동의체크를 안해서 응답없을 것
GET/POST 모두 지원하지만
- 토큰을 통한 사용자 정보 조회는 POST로 한다. (GET으로하면 주소에 남으니까)
- 요청 주소 : https://kapi.kakao.com/v2/user/me
- 헤더 값
Authorization: Bearer ${ACCESS_TOKEN}
Content-type: application/x-www-form-urlencoded;charset=utf-8
사용자 정보 조회는 헤더값만 필요!
* ${ACCESS_TOKEN} 자리에는 엑세스 토큰을 넣어주면 된다.
* Bearer 하고 한칸 띄우고 엑세스 토큰 더해주기
[UserController]
1. RestTemplate 라이브러리를 써서 http 요청을 쉽게 할 수 있다.
2. HttpHeaders2 객체를 생성하여 헤더값을 담는다.
* 위에 엑세스 토큰 발급 요청할때 쓴 거 복붙하기
// 사용자 정보 요청하기
RestTemplate rt2 = new RestTemplate();
// HttpHeaders 오브젝트 생성
HttpHeaders headers2 = new HttpHeaders();
headers2.add("Authorization", "Bearer "+oauthToken.getAccess_token());
headers2.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
// HttpHeaders만 오브젝트에 담기
HttpEntity<MultiValueMap<String, String>> kakaoProfileRequest2 =
new HttpEntity<>(headers2);
// Http 요청하기 - POST방식으로 그리고 response 변수의 응답 받음
ResponseEntity<String> response2 = rt2.exchange(
"https://kapi.kakao.com/v2/user/me", //토큰 발급 요청 주소
HttpMethod.POST, //요청 메서드 post
kakaoProfileRequest2,
String.class // 응답받을 타입
);
System.out.println(response2.getBody());
return response2.getBody();
}
HttpHeaders 객체를 생성하여 헤더값 넣기
HttpHeaders headers2 = new HttpHeaders();
headers2.add("Authorization", "Bearer "+oauthToken.getAccess_token());
headers2.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
- Authorization: Bearer ${ACCESS_TOKEN} Bearer 하고 한칸 띄우기!
- Content-type: application/x-www-form-urlencoded;charset=utf-8
회원정보 요청했을 시 결과
return response2.getBody();
위 결과를 자바 오브젝트로 변경
System.out.println(response2.getBody());
콘솔창 복사해서 아래의 사이트에 붙여넣고 Priview 클릭하면 자바 오브젝트로 변경
콘솔창은 {"id":123465636."connected_at":"~"} 쌍따옴표가 없으면 오류가 났는데 콘솔창에는 쌍따옴표로 돼있어서 오류안남
https://www.jsonschema2pojo.org/ 사이트 에 들어간다.
jsonschema2pojo
Reference properties For each property present in the 'properties' definition, we add a property to a given Java class according to the JavaBeans spec. A private field is added to the parent class, along with accompanying accessor methods (getter and sette
www.jsonschema2pojo.org
만들어진 자바 오브젝트들을 모두 복사해서 KakaoProfile 클래스에 넣기
[KakaoProfile]
☆ 주의 할 점
변수명들을 카멜 표기법(camelCase)에서 스네이크 표기법(snake_case)으로 통일해준다.
package com.cos.blog.model;
import lombok.Data;
@Data
public class KakaoProfile {
public Long id;
public String connected_at;
public Properties properties;
public KakaoAccount kakao_account;
@Data
public class Properties {
public String nickname;
public String profile_image;
public String thumbnail_image;
}
@Data
public class KakaoAccount {
public Boolean profile_nickname_needs_agreement;
public Boolean profile_image_needs_agreement;
public Profile profile;
public Boolean has_email;
public Boolean email_needs_agreement;
public Boolean is_email_valid;
public Boolean is_email_verified;
public String email;
@Data
public class Profile {
public String nickname;
public String thumbnail_image_url;
public String profile_image_url;
public Boolean is_default_image;
}
}
}
*@Data 붙여야 갖다쓸수있음.
위 사용자 정보들을 Kakaoprofile 클래스에 넣기
[UserController]
제이슨에서 자바오브젝트로 바꾸기위해 ObjectMapper 라이브러리 사용한다.
* 엑세스 토큰에서 쓴거 복붙해서 사용하기
ObjectMapper objectMapper2 = new ObjectMapper();
KakaoProfile kakaoProfile = null;
try {
kakaoProfile = objectMapper2.readValue(response2.getBody(), KakaoProfile.class);
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
System.out.println("카카오 아이디(번호) : "+kakaoProfile.getId());
System.out.println("카카오 이메일 : "+kakaoProfile.getKakao_account().getEmail());
return response2.getBody();
}
readValue() 를 사용하면 kakaoProfile 객체를 제이슨 데이터에서 자바obj 으로 변경
kakaoProfile = objectMapper2.readValue(response2.getBody(), KakaoProfile.class);
: response.getBody() ▶ KakaoProfile.class 에 담는다.
이제 KakaoProfile에 사용자 정보가 담김
- return response2.getBody();
- 로그인 했을때 콘솔창
- System.out.println("카카오 아이디(번호) : "+kakaoProfile.getId());
System.out.println("카카오 이메일 : "+kakaoProfile.getKakao_account().getEmail());
'Spring boot | 블로그 만들기' 카테고리의 다른 글
블로그 만들기 | 게시글 댓글 기능과 무한 참조 (0) | 2022.11.24 |
---|---|
블로그 만들기 | [카카오API] 카카오 로그인시 회원통합 (1) (1) | 2022.11.19 |
블로그 만들기 | [카카오API] .getBody() , ObjectMapper 라이브러리(3) (1) | 2022.11.18 |
블로그 만들기 | [카카오 API] 엑세스 토큰 받기(2) (0) | 2022.11.17 |
블로그 만들기 | 회원 정보 수정하기2 - Authentication객체 만들어 세션값 변경 (0) | 2022.11.17 |