Java/etc

[JAVA] HttpClient Rest API 생성

고플밍 2025. 6. 25. 15:17

 

HttpClient 공통 Util을 소개합니다.

 

package x.util;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;

/**
 * packageName    : x.util;
 */
public class HttpClientUtil {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * Get t.
     *
     * @param <T>          the type parameter
     * @param url          the url
     * @param headers      the headers
     * @param responseType the response type
     * @return the t
     * @throws IOException          the io exception
     * @throws InterruptedException the interrupted exception
     */
    public static <T> T get(String url, Map<String, String> headers, Class<T> responseType) throws IOException, InterruptedException {
        HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(url)).GET();
        addHeaders(builder, headers);
        HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
        return objectMapper.readValue(response.body(), responseType);
    }

    /**
     * Post t.
     *
     * @param <T>          the type parameter
     * @param url          the url
     * @param requestBody  the request body
     * @param headers      the headers
     * @param responseType the response type
     * @return the t
     * @throws IOException          the io exception
     * @throws InterruptedException the interrupted exception
     */
    public static <T> T post(String url, Object requestBody, Map<String, String> headers, Class<T> responseType) throws IOException, InterruptedException {
        String json = objectMapper.writeValueAsString(requestBody);
        HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(url)).POST(HttpRequest.BodyPublishers.ofString(json));
        addHeaders(builder, headers);
        HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
        return objectMapper.readValue(response.body(), responseType);
    }

    /**
     * Put t.
     *
     * @param <T>          the type parameter
     * @param url          the url
     * @param requestBody  the request body
     * @param headers      the headers
     * @param responseType the response type
     * @return the t
     * @throws IOException          the io exception
     * @throws InterruptedException the interrupted exception
     */
    public static <T> T put(String url, Object requestBody, Map<String, String> headers, Class<T> responseType) throws IOException, InterruptedException {
        String json = objectMapper.writeValueAsString(requestBody);
        HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(url)).PUT(HttpRequest.BodyPublishers.ofString(json));
        addHeaders(builder, headers);
        HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
        return objectMapper.readValue(response.body(), responseType);
    }

    /**
     * Delete t.
     *
     * @param <T>          the type parameter
     * @param url          the url
     * @param headers      the headers
     * @param responseType the response type
     * @return the t
     * @throws IOException          the io exception
     * @throws InterruptedException the interrupted exception
     */
    public static <T> T delete(String url, Map<String, String> headers, Class<T> responseType) throws IOException, InterruptedException {
        HttpRequest.Builder builder = HttpRequest.newBuilder().uri(URI.create(url)).DELETE();
        addHeaders(builder, headers);
        HttpResponse<String> response = httpClient.send(builder.build(), HttpResponse.BodyHandlers.ofString());
        return objectMapper.readValue(response.body(), responseType);
    }

    private static void addHeaders(HttpRequest.Builder builder, Map<String, String> headers) {
        if (headers != null) {
            headers.forEach(builder::header);
        }
    }
}

 

Map<String, String> headers 은 Header

Object requestBody 는 parameter 

Class<T>의 responseType은 응답값을 받고자하는 class 타입을지정

   

 

사용법은 아래와 같음

public Map<String, Object> httpClientTest(@PathVariable String method) throws IOException, InterruptedException {
        Map<String, Object> response;
        if ("get".equals(method)) {
            response = HttpClientUtil.get(
            "https://jsonplaceholder.typicode.com/posts/1",
                Map.of("Content-type", "application/json; charset=UTF-8"),
                Map.class
            );
        } else
        if ("post".equals(method)) {
            Map<String, Object> map = new HashMap<>();
            map.put("title", "foo");
            map.put("body", "bar");
            map.put("userId", 1);
            response = HttpClientUtil.post(
                "https://jsonplaceholder.typicode.com/posts",
                map,
                Map.of("Content-type", "application/json; charset=UTF-8"),
                Map.class
            );
        } else
        if ("put".equals(method)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", 1);
            map.put("title", "foo");
            map.put("body", "bar");
            map.put("userId", 1);
            response = HttpClientUtil.put(
                "https://jsonplaceholder.typicode.com/posts/1",
                map,
                Map.of("Content-type", "application/json; charset=UTF-8"),
                Map.class
            );
        } else {
            Map<String, String> map = new HashMap<>();
            response = HttpClientUtil.delete(
            "https://jsonplaceholder.typicode.com/posts/1",
                map,
                Map.class
            );
        }
        return null;
    }

 

 

Gradle 기준 아래 의존성 추가

dependencies {
    implementation("com.fasterxml.jackson.core:jackson-databind:2.17.0")
}

 

 

https://jsonplaceholder.typicode.com

 

JSONPlaceholder - Free Fake REST API

{JSON} Placeholder Free fake and reliable API for testing and prototyping. Powered by JSON Server + LowDB. Serving ~3 billion requests each month.

jsonplaceholder.typicode.com

 

위 사이트는 REST API 테스트를 제공해주는 사이트입니다.

호출 이후 결과도 HTTP Method 에 따라 가이드가 있으니 이용하세요!