빅토리 코딩
article thumbnail
728x90
반응형
api와 api 사이에 http 통신을 할때 지금 회사에서는  httpClient를 만들어서 httpGet이나 httpPost객체를 만들어 execute하는 방식이었다. 그리고 통신 후 받는 model(Vo)들은 전부  Map으로 받아 Map으로 처리하는 형태 이다. swagger와 spring validation을 점점 사용하는 형태로 가면서 Map이 아닌 model(Vo)를 만들어서 사용하기 시작하였다. 그래서 제너릭을 이용하여 model(Vo)를 바로 통신 할수 있는 httpconnection을 만들어 보고있었는데 Spring에서 RestTemplate을 사용하면 HTTP 요청 및 응답 데이터를 쉽게 처리할 수 있다는 설명을 보고 RestTenplate를 사용하여 만들기로 했다...!

개요

HttpConnection

httpConnection은 HTTP 프로토콜을 사용하여 데이터를 주고 받는것이다. HttpConnection 클래스를 사용하여 URL에 대한 요청을 보내고, 서버로부터의 응답을 처리한다. 이 클래스는 GET, POST, PUT, DELETE 등의 HTTP 메서드
를 지원하며, 서버와의 데이터 통신 중에 예외 처리 및 에러 핸들링 기능도 제공한다.

RestTemplate

Spring 에서 제공하는 웹 서비스를 호출 라이브러리이다. RestTemplate을 사용하면 HTTP 요청 및 응답 데이터를 쉽게 처리할 수 있으며, Spring의 다른 기능과 함께 사용하면 더욱 강력한 웹 애플리케이션을 구축할 수 있다. 또한  Java 객체와 JSON 데이터 간의 변환도 쉽게 가능하다.

 

구현

https://github.com/victory940209/java_util.git

 

GitHub - victory940209/java_util

Contribute to victory940209/java_util development by creating an account on GitHub.

github.com

- config 설정

RestTemplate를 사용하기 위해 config 설정을 해준다.

@Configuration(proxyBeanMethods = false)
public class MyConfiguration {

    @Bean
    RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }
}

- httpConnectionUtil

public class HttpUrlConnectUtil {

	@Autowired
	RestTemplate restTemplate;

	/**
	 * @Desc : get 방식의 통신
	 * @Method : httpGetConnection
	 * @param: (url, req 객체, httpHeader(Map 형식), 객체의 클래스)
	 * @Desc :
	 * @return : param으로 받은 객체 그대로
	 */
	public <T, K> K apiGet(String url, T obj, Map<String, Object> header, Class<K> cls) throws Exception {

		HttpHeaders reqheader = setHeader(header);
		HttpEntity<T> entity = new HttpEntity<>(obj, reqheader);

		ResponseEntity<K> respEntity = restTemplate.getForEntity(url, cls, entity);

		return respEntity.getBody();

	}

	/**
	 * @Desc : post 방식의 통신 시 원하는 객체로 통신하는 util
	 * @Method : httpPostConnection
	 * @param : (url, req 객체, httpHeader(Map 형식), 객체의 클래스)
	 * @Desc :
	 * @return : param으로 받은 객체 그대로
	 */
	public <T, K> K apiPost(String url, T obj, Map<String, Object> header, Class<K> cls) throws Exception {

		HttpHeaders reqheader = setHeader(header);
		HttpEntity<T> entity = new HttpEntity<>(obj, reqheader);

		ResponseEntity<K> respEntity = restTemplate.postForEntity(url, entity, cls);

		return respEntity.getBody();

	}

	/**
	 * @Desc : header 값 세팅
	 * @Method : setHeader
	 * @param : (httpHeader(Map 형식))
	 * @Desc : param으로 들어온 Map을 전부 HttpHeaders 객체에 넣어 반환
	 * @return : HttpHeaders
	 */
	public HttpHeaders setHeader(Map<String, Object> headers) throws Exception {

		HttpHeaders header = new HttpHeaders();

		for (Entry<String, Object> elem : headers.entrySet()) {
			if (!"".equals(elem.getValue()) && elem.getValue() != null) {
				header.set(elem.getKey(), elem.getValue().toString());
			}
		}
		return header;
	}

}

method 내용을 보면

- <T, K> : T,K라는 객체를 제너릭으로 선언 함으로 사용 가능하다. 반환 객체가 K이므로 K의 객체로 반환한다는 뜻이다.

- Class<K> cls : K 객체가 무엇인지 세팅하는 부분 ex) Map.class

- HttpEntity<T> : T객체를 http통신을 할때 body나 Param에 넣는다는 뜻이다. 또한 HttpHeaders도 선언할때 같이 넣어 줄수 있다.

- ResponseEntity<K> : RestTamplate를 통해 http통신 후 받은 값들이 있는객체로서 일반적으로 컨트롤러 반환값으로도 쓴다. ResponseEntity안에는 응답코드(HttpStatus), 응답데이터(body) 등의 정보들이 모두 들어있다.

 

- Controller

@Slf4j
@RestController
public class TestController {

	@Autowired
	HttpUrlConnectUtil apiCon;
 	
    @PostMapping(value = "/apiConPostVo")
	public ResultVo apiConPostVo(@RequestBody TestVo param, @RequestHeader Map<String, Object> requestHeader)
			throws Exception {

		ResultVo res = new ResultVo();
        String resulturl = "http://127.0.0.1:8080/postTest";
        
		try {

			res = apiCon.apiPost(resulturl, param, requestHeader, ResultVo.class);
			log.info("###end-point`s return value : " + res);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return res;
	}
    
	@PostMapping(value = "/apiConGetVo")
	public TestVo apiConGetVo(@RequestBody TestVo param, @RequestHeader Map<String, Object> requestHeader)
			throws Exception {
		TestVo res = new TestVo();
        String resulturl = "http://127.0.0.1:8080/GetTest";
		
        try {

			res = apiCon.apiGet(resulturl, param, requestHeader, TestVo.class);
			log.info("###end-point`s return value : " + res);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return res;
	}    
 
 }

 

테스트

test용 spring boot 생성

https://github.com/victory940209/testspringboot.git

 

GitHub - victory940209/testspringboot

Contribute to victory940209/testspringboot development by creating an account on GitHub.

github.com

testHttpSpringboot를 받거나 만들면 된다.

-controller

@RestController
public class TestController {

	@PostMapping(value = "/PostTest")
	public ResultVo PostTest(@RequestBody TestVo param) throws Exception {

		log.debug("param : " +  param);

		return ResultVo.builder().result("PostTest").resultMsg("PostTest 성공").build();

	}

	@GetMapping(value = "/GetTest")
	public ResultVo GetTest(@RequestParam Map<String, Object> param) throws Exception {

		log.debug("param : " +  param);


		return ResultVo.builder().result("GetTest").resultMsg("GetTest 성공").build();

	}

}

- TestVo

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestVo {

	@JsonProperty("test1")
	private String test1;

	@JsonProperty("test2")
	private String test2;

	@JsonProperty("test3")
	private String test3;

}

- ResultVo

@Builder
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class ResultVo {


	@JsonProperty("resultMsg")
	private String resultMsg;

	@JsonProperty("result")
	private String result;

}

띄우고 기존에 만들었던 소스에서 /apiConGetVo와  /apiConPostVo를 호출 해보자

둘다 정상적으로 반환했다 HttpUrlConnectUtil에서객체를 다양하게 변경해서 쏘아보아도 잘되는것을 확인했다.!

728x90
반응형
profile

빅토리 코딩

@빅토리 코딩

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

검색 태그