본문 바로가기 메뉴 바로가기

대표이미지

RestTemplate를 통한 REST-API 활용

2023. 8. 3.
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer "+access_token);

HttpEntity<MultiValueMap<String, String>> http_entity = new HttpEntity<>(null, headers);

// 
ResponseEntity<String> result 
= restTemplate.exchange("http://someUrl.com/getUserinfo/someId",HttpMethod.GET, http_entity ,String.class);

GET 방식 (exchange : 모든 Method 사용 가능)

.

.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization","Bearer "+manager_token);

JSONObject user_job = new JSONObject();
user_job.put("firstName", vo.getFirstName());
user_job.put("lastName", vo.getLastName());
user_job.put("email", vo.getEmail());
user_job.put("enabled", true);
user_job.put("username", vo.getUsername());

HttpEntity<String> http_entity = new HttpEntity<String>(user_job.toString(), headers);
URI create_user_uri = new URI("http://somekindofUrl.com/createUser");
restTemplate.postForObject(create_user_uri, http_entity, String.class);

POST 방식 (json 데이터 전송 시)

.

.

RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
map.add("grant_type", CredentialRepresentation.PASSWORD);
map.add("client_id", KeyCloakProperties.clientId);
map.add("client_secret", KeyCloakProperties.clientSecret);
map.add("username", username);
map.add("password", password);

HttpEntity<MultiValueMap<String, String>> http_entity = new HttpEntity<>(map, null);

Object result = restTemplate.postForObject("http://somekindofUrl.com/getToken", http_entity, String.class);

POST 방식 (일반 formdata 전송 시)

.

.

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", "Bearer "+manager_token);
/*
{
    "type":"password",
    "temporary": false,
    "value": "62@changePassword!@#"
}	// 의 JSON 형식
*/
JSONObject pass_job = new JSONObject();
pass_job.put("type", "password");
pass_job.put("temporary", false);
pass_job.put("value", new_password);

HttpEntity<String> http_entity = new HttpEntity<String>(pass_job.toString(), headers);
URI reset_pass_uri = new URI("http://somekindofurl.com/update");
restTemplate.put(reset_pass_uri, http_entity);

PUT 방식 ( json 데이터 + header 값 전송 )

.

.

RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", "Bearer "+manager_token);
String delete_url = "http://somekindofUrl.com/delete";

HttpEntity<?> http_entity = new HttpEntity<Object>(headers);

ResponseEntity<String> result 
= restTemplate.exchange(delete_url, HttpMethod.DELETE, http_entity, String.class);

DELETE 방식 

.

.

 

댓글 갯수
TOP