본문 바로가기

IT, 인터넷/JAVA, 스프링부트

스프링, 스프링부트 resttemplate 사용하기 (외부와 연결하는 restapi)

반응형

스프링, 스프링부트에서 resttemplate를 사용하는건 아주 간단 합니다.

외부와 통신을 할때 resttemplate를 사용을 하면 아주 편하게 통신이 가능 합니다.

저는 스프링부트 기준으로 설명을 하겠습니다. 요즘에는 스프링보다는 스프링부트를 많이 쓰거든요.

그리고 스프링부트가 스프링보다 버전 충돌등 이런게 없어서 전 개인적으로 스프링부트를 추천 합니다.

먼저 config를 만들어 주어야 합니다.

 

RestTemplateConfig.java

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.time.Duration;

 

@Configuration
public class RestTemplateConfig {

@Value("${api.timeout}")
    private int timeOut;

@Value("${api.charset}")
    private String charSet;

@Bean
    public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
                .requestFactory(() -> new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()))
                .setConnectTimeout(Duration.ofMillis(timeOut)) // connection-timeout
                .setReadTimeout(Duration.ofMillis(timeOut)) // read-timeout
                .additionalMessageConverters(new StringHttpMessageConverter(Charset.forName(charSet)))
                .build();
    }
}

 

이렇게 config 패키지를 만들어서 RestTemplateConfig를 추가해 줍니다.

---apllication.yml

api:
  timeout: 120000
  charset: UTF-8 

 

---application.properties

api.timeout=120000
api.charset=UTF-8 

그리고 yml 파일이나 properties 파일에 저렇게 추가를 해주면 설정은 끝 입니다.

 

RestTemplateService.java
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

 

@Service
public class ExternalServiceImpl {

private ApiService<ResponseEntity<String>> apiService;

    @Autowired
    public ExternalServiceImpl(ApiService<ResponseEntity<String>> apiService) {
        this.apiService = apiService;
    }
    
    public ResponseEntity<String> callPostExternalServerJson(Map<String, String> paramMap) {
    
     HttpHeaders headers = new HttpHeaders(); 
     headers.setContentType(MediaType.APPLICATION_JSON);
     HttpEntity<String> request = 
         new HttpEntity<String>(paramMap.get("json"), headers);
    
        return apiService.getExternalPostJson(paramMap.get("url"), request);
    }
}

 

서비스 자바 입니다. Map 을 파라미터로 넘겨서 처리하고 json으로 넘기는 방식 입니다.

헤더를 보내 주어야 json으로 인식을 해서 외부에서 처리가 가능 합니다.

 

ApiService.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

 

@Service
public class ApiService<T> {

    private RestTemplate restTemplate;
    
    @Autowired
    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }
    
    public ResponseEntity<String> getExternalPostJson(String url, HttpEntity<String> parameters) {

     return restTemplate.postForEntity(url, parameters, String.class);
    }
}

 

여기서 url, 파리미터로 외부로 보내 줍니다.

이제 controller와 jsp 파일을 작성해 보겠습니다.

 

RestConroller.java

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

 

@Controller
public class RestConroller {

@Autowired
    ExternalService restTemplateService;

 

@RequestMapping(value = "/policymng/policy.ajax", method = {RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    @ResponseBody
    public String rmtdeploycall(@RequestParam Map<String, String> paramMap, 
     HttpServletRequest request, HttpServletResponse response) {
    
     ResponseEntity<String> result = restTemplateService.callPostExternalServerJson(paramMap);

        return result.getBody();
    }

}

 

restTest.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"

    pageEncoding="EUC-KR"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="EUC-KR">

    <title>Insert title here</title>

    <Script>

        function remoteDbDel() {

 

        var jsonData = new Object();

        jsonData.test = "test";

 

        $.ajax({

                type : "POST",

                url : "/restTest.ajax",

                async: true,

                data : { "json": JSON.stringify(jsonData),

                    "url": "/test.url" },

                success : function(data) {

                

                    alert("성공" + data);

                },

                error: function (xhrstatuserror) {

                    console.log("code:"+xhr.status+"\n"+"message:"+xhr.responseText+"\n"+"error:"+error);

                }

            });

        }

    </Script>

</head>

<body>

    <button value="test" onClick="remoteDbDel()" />

</body>

</html>

 

이렇게 컨트롤러와 jsp를 만들어서 테스트를 하면 외부와 통신이 가능합니다.

스프링부트를 사용하면 resttemplate로 간단하게 만들어서 외부와 통신이 가능합니다.

 

 

 

반응형