1. 의존성 추가
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.15</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
2. GetMapping : 헤더에 토큰을 받아 전달하는 경우
@GetMapping("repositories/sources")
public ResponseEntity<ResponseDto> sources(@RequestHeader(value="Authorization") String acc_tk) throws Exception {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8"))); //필요에 따라
httpHeaders.set("Authorization", acc_tk);
httpHeaders.set("Accept", "*/*");
HttpEntity entity = new HttpEntity(httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<ResponseDto> responseEntity = restTemplate.exchange(BASE_URL + "repositories", HttpMethod.GET, entity, ResponseDto.class);
return responseEntity;
}
3. PostMapping
@Autowired
private ObjectMapper objectMapper;
@PostMapping("login")
public Map<String, Object> login(@RequestBody Map<String, Object> param) throws JsonProcessingException, JSONException {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8")));
HttpEntity entity = new HttpEntity(objectMapper.writeValueAsString(param), httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> responseEntity = restTemplate.exchange(BASE_URL + "auth", HttpMethod.POST, entity, String.class);
//응답 가공
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("username", param.get("username"));
userInfo.put("password", param.get("password"));
userInfo.put("token", responseEntity.getBody());
return userInfo;
}
'Develop > Spring' 카테고리의 다른 글
[Spring, JPA] Page 2 of 1 containing UNKNOWN instances (0) | 2023.01.16 |
---|---|
[SpringBoot] jar파일 생성 및 실행 (4) | 2023.01.12 |
[VSCode] vscode에서 Spring Boot Maven 프로젝트 생성하기(환경구성) (0) | 2022.11.16 |
[SpringBoot] Thymeleaf 문법 정리 (0) | 2022.11.15 |
[SpringBoot/STS4] Thymeleaf 프로젝트 생성하기 (0) | 2022.11.15 |