일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- postgis
- 인증
- 본인인증
- 공동인증서
- IntelliJ
- db
- docker
- deepseek vs chatgpt
- AWS
- AOP
- spring security
- 코틀린
- 본인확인
- Spring Boot
- ktlin
- Mono
- Kotlin
- PostgreSQL
- webflux
- exception
- Flux
- netty
- 딥시크
- 허깅 페이스
- Spring
- NGINX
- 컨퍼런스
- 로그인
- 보안
- API
- Today
- Total
[수미수의 개발 브로구]
[Java] RestTemplate vs. Apache HttpClient 본문
들어가기 전
Http 통신을 위한 방법
URLConnection
URLConnection 은 URL이 가리키는 리소스에 대한 연결을 나타내는 추상 클래스이다. java.net 패키지에 있으며, URL 주소에, Get, Post로 데이터를 전달 할 수 있다. 하지만, 응답 코드가 4xx, 5xx 면 IOException이 발생, 타임아웃 설정 불가, 쿠키 제어가 불가 하다.
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
출처 : https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
HttpClient
3.x의경우 apache commons 의 프로젝트, 4.x 부터 Apache HttpComponents로 불린다. 4.x는3.x 버전에서 개선되었으며 둘간의직접적인호환성은 제공하지 않으며, 4.x 부터는쓰레드 안정성기능을 많이제공 한다. URLConnection과 비교하면, 모든 응답 코드를 읽을 수 있고 ,타임아웃 설정, 쿠키 제어가 가능하다. 하지만, 반복적인 코드가 길며, json 또는 xml 과 같은 컨텐츠 타입에 따라 별도 메시지 컨버팅이 필요 하다.
/** HttpClient 3.x **/
HttpClient httpclient = new HttpClient();
GetMethod httpget = new GetMethod("http://www.myhost.com/");
try {
httpclient.executeMethod(httpget);
Reader reader = new InputStreamReader(
httpget.getResponseBodyAsStream(), httpget.getResponseCharSet());
// consume the response entity
} finally {
httpget.releaseConnection();
}
출처 : http://hc.apache.org/httpclient-3.x/performance.html
/** HttpComponent 4.x **/
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("http://localhost/");
System.out.println("Executing request " + httpget.getRequestLine());
// Create a custom response handler
ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
public String handleResponse(
final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
if (status >= 200 && status < 300) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
} else {
throw new ClientProtocolException("Unexpected response status: " + status);
}
}
};
String responseBody = httpclient.execute(httpget, responseHandler);
System.out.println("----------------------------------------");
System.out.println(responseBody);
} finally {
httpclient.close();
}
출처 : https://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientWithResponseHandler.java
RestTemplate
HttpClient는 Http를 사용하여 통신하는 범용 라이브러리이지만, 사용을 위한 중복 코드 또는 설정 코드들이 많아진다. 스프링에서는여느 template과마찬가지로 보일러플레이트 코드를최대한줄여주며, 이에 반해, RestTemplate는 HttpClient를 추상화하였으며, 자동으로 json, xml을 컨버팅 하는 기능도 제공한다.
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, "42", "21");
Map<String, String> vars = new HashMap<String, String>();
vars.put("hotel", "42");
vars.put("booking", "21");
String result = restTemplate.getForObject("http://example.com/hotels/{hotel}/bookings/{booking}", String.class, vars);
So..??
httpclient와restemplate 의 속도차이는 크게 나지 않으며, reste template 의경우 사용자입장에서 불필요한 코드의양을 줄일수있다. 그리고 Spring 에서 DI를이용하여 쉽게사용할수있는장점이 있다. 물론, Rest Template도 내부적으로 httpclient 를사용하지만, 결국에는 불필요한 코드를 줄이고 쉽게 사용할 수 있는차이점인것 같다.
References
RestTemplate (정의, 특징, URLConnection, HttpClient, 동작원리, 사용법, connection pool 적용)
참조문서 : https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html1. RestTemplate이란?spring 3.0 부터 지원한다. 스프링에서 제공하는 http 통신에 유용하게 쓸 수 있는
sjh836.tistory.com
[java] Spring RestTemplate
apache의 httpclient와 spring의 restTemplate비교
vnthf.github.io
'Language & Framework > Java' 카테고리의 다른 글
[Java] Java Background 실행 (0) | 2023.09.22 |
---|---|
[Tomcat] 멀티 인스턴스 사용하기 (0) | 2023.09.22 |
[IntelliJ] IntelliJ 빌드 시 Command line is too long. Shorten command line for 오류 발생 (0) | 2023.09.01 |
[Java] Java Date (0) | 2023.08.10 |
[Kotlin] 신규 프로젝트 생성 후 "Cannot access script base class 'org.gradle.kotlin.dsl.KotlinBuildScript'" 나왔을때.. (0) | 2023.08.10 |