[JAVA] HttpEntity 객체 만들기 (RequestBody 만들기)

유존돌돌이·2022년 3월 1일
0

JAVA

목록 보기
20/22

아래의 예는 카카오 OAuth 토큰발행하기 위해 POST 호출하는 부분이다.

		// RequestBody만드는 라이브러리들 
		// Retrofit2
		// OkHttp
		// RestTemplate
		RestTemplate rt = new RestTemplate();
		
		// 해더 만들기 
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
		
		// 바디 만들기 (HashMap 사용 불가!)
		MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
		params.add("grant_type", "authorization_code");
		params.add("client_id", ApiConfig.KAKAO_OAUTH_KEY.getContent());
		params.add("redirect_uri", ApiConfig.KAKAO_OAUTH_CALLBACK.getContent());
		params.add("code", code);
		
		
		// 해더와 바디를 하나의 오브젝트로 만들기
		HttpEntity<MultiValueMap<String, String>> kakaoTokenRequest =
				new HttpEntity<>(params, headers);
		
		// Http 요청하고 리턴값을 response 변수로 받기
		ResponseEntity<String> response = rt.exchange(
				"https://kauth.kakao.com/oauth/token", // Host
				HttpMethod.POST, // Request Method
				kakaoTokenRequest,	// RequestBody
				String.class);	// return Object

0개의 댓글