Develop/Spring

[SpringBoot] RestTemplate을 이용하여 http 요청보내기

wltn.js 2023. 2. 12. 03:08

 

 

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;
    }