JAVA

HttpURLConnection | RestTemplate | WebClient

잔망루피 2023. 12. 28. 12:00
반응형
개발 환경: OpenJDK 17, Spring Boot 3.1.7
사용한 API: https://developers.kakao.com/docs/latest/ko/daum-search/dev-guide#search-book

 

 

 

HttpURLConnection

public abstract class HttpURLConnection extends URLConnection

JDK 1.1부터 내장하고 있는 클래스다.

각 HttpURLConnection 객체는 단일 요청을 만드는데 사용된다.

하지만, 네트워크 연결에 따라서 HTTP 서버는 공개적으로 다른 인스턴스로부터 공유될 수 있다.

요청이 끊어진 후 InputStream 또는 OutputStream에서 close() 메서드 호출하는 것은 어떠한 공유된 영구적인 연결에도 영향을 미치지 않는다.

disconnect() 메서드는 원하는 시점에 소켓을 닫을 수 있다.

자동 redirection이 가능하면, 요청은 다른 대상으로 redirect 될 수 있고, 호출자는 host/URL에 redirect할 연결 권한을 가지고 있어야 한다.

 

 

 

RestTemplate

  • 동기식 클라이언트라서 Concurrent한 작업은 지원하지 않음 
  • Spring 6.1부터는 RestClient 사용을 권장하고 있음 
@GetMapping("/rest-template")
public ResponseEntity<?> testResTemplate () {
    String url
            = "https://dapi.kakao.com/v3/search/book?target=title&query=미움받을 용기";

    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "KakaoAK " + key);

    HttpEntity request = new HttpEntity(headers);

    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.exchange(url, HttpMethod.GET, request, String.class);
}

 

실행 결과

 

 

 

WebClient

  • Single Thread + Non-blocking 방식으로 동작
  • Spring WebFlux에서 HTTP Client로 사용된다. 
implementation 'org.springframework:spring-webflux:6.1.2'

WebClient를사용하기 위해서는 spring-webflux 의존성을 추가한다. 

@GetMapping("/web-client")
public Flux<String> testWebClient() {
    WebClient webClient = WebClient.create("https://dapi.kakao.com/v3/search/book?target=title&query=미움받을 용기");
    return webClient.get()
            .header("Authorization", "KakaoAK " + key)
            .retrieve()
            .bodyToFlux(String.class);
}

key는 @Value 어노테이션을 이용해서 application.properties에 기입한 REST API Key를 받도록 했다.

 

실행 결과

 

 

 

 

 


참고 👇👇👇

https://docs.oracle.com/javase/8/docs/api/java/net/HttpURLConnection.html

 

HttpURLConnection (Java Platform SE 8 )

Returns the error stream if the connection failed but the server sent useful data nonetheless. The typical example is when an HTTP server responds with a 404, which will cause a FileNotFoundException to be thrown in connect, but the server sent an HTML hel

docs.oracle.com

 

https://www.codejava.net/java-se/networking/how-to-use-java-urlconnection-and-httpurlconnection

 

How to use Java URLConnection and HttpURLConnection

 

www.codejava.net

 

반응형