PHpullh
학습 라이브러리/Java/HTTP Client (java.net.http)

JAVA · 파일/IO

HTTP Client (java.net.http)

Java 11+의 내장 HTTP 클라이언트로 REST API를 호출합니다.

파일/IO중급HttpClientHTTPRESTJava11

핵심 설명

Java 11+의 내장 HTTP 클라이언트로 REST API를 호출합니다.

Java code

import java.net.http.*;
import java.net.URI;
import java.time.Duration;

public class HttpClientDemo {
    public static void main(String[] args) throws Exception {
        // HttpClient 생성 (재사용 권장)
        HttpClient client = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_2)
            .connectTimeout(Duration.ofSeconds(10))
            .followRedirects(HttpClient.Redirect.NORMAL)
            .build();

        // GET 요청
        HttpRequest getReq = HttpRequest.newBuilder()
            .uri(URI.create("https://httpbin.org/get"))
            .header("Accept", "application/json")
            .timeout(Duration.ofSeconds(30))
            .GET()
            .build();

        HttpResponse<String> response = client.send(
            getReq, HttpResponse.BodyHandlers.ofString());
        System.out.println("상태: " + response.statusCode());
        System.out.println("본문: " + response.body().substring(0, 100));

        // POST 요청
        String json = "{\"name\":\"test\",\"value\":42}";
        HttpRequest postReq = HttpRequest.newBuilder()
            .uri(URI.create("https://httpbin.org/post"))
            .header("Content-Type", "application/json")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

        // 비동기 요청
        client.sendAsync(postReq, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenAccept(body -> System.out.println("비동기: " + body.length()))
            .join();
    }
}

학습 팁

HttpClient는 스레드 안전하고 HTTP/2를 지원합니다. sendAsync()로 비동기 요청을 보내면 CompletableFuture가 반환됩니다.

주의할 점

HttpClient 인스턴스를 매 요청마다 생성하면 커넥션 풀링 이점을 잃습니다. 싱글턴으로 재사용하세요.

자주 묻는 질문

HTTP Client (java.net.http)란 무엇인가요?

Java 11+의 내장 HTTP 클라이언트로 REST API를 호출합니다.

HTTP Client (java.net.http) 학습 시 주의할 점은 무엇인가요?

HttpClient 인스턴스를 매 요청마다 생성하면 커넥션 풀링 이점을 잃습니다. 싱글턴으로 재사용하세요.