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 에 따라 가이드가 있으니 이용하세요!  

Integer는 null 입력이 가능하다.

 

Integer 변수에 null이 입력되었을 경우

if문으로 숫자와 비교했을 때 바른 문법이라고 생각했다.

그러나, Integer에 null이 입력했을 경우 숫자와 비교했을 때 아래와 같은 에러가 발생하였다.

습관적으로

NullPointerException이 발생하여 num1에 null이 입력되어 발생하는 줄로만 인식하였다.

그렇다면, 처음 변수 선언하는곳에서 에러가 발생해야 하는게 아닌가?

Integer 변수에 null이 입력되어 발생하는게 아니라,

null과 정수(int 자료형)를 비교하려고 하기 때문에 발생하는 에러였다.

 

아래를 살펴보자.

정수와 null을 비교해보자. 아예 int와 null 타입자체를 비교할 수 없다고 에러가 발생한다.

 

 

 

습관은 무서운 것이다.

항상, 한 발 물러서서 접근하는 자세가 필요하다.

 

이클립스에서, 파일 검색 중 하나 인 Open Resource (Ctrl + Shift + R)을 사용 할 때

 

target 에 포함되어있는 파일까지 검색되어, 여간 걸리적 거리는게 아니었다.

 

해당 프로젝트 우클릭 후 프로퍼티에 들어간 다음, 리소스 안에 리소스 필터를 찾는다.

 

Properties -> Resource -> Resource Filters을 열면, 아래와 같은 이미지가 나온다.

 

 

 

 

쿠팡!

무료체험 후 월 4,990원이 결제됩니다. 와우 멤버십 이용약관에 동의합니다.

loyalty.coupang.com

"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."

 

 

 

 

여기서 , Add Filter를 누른 후

 

Exclude all 체크

 

Folders 체크

 

아래, target을 입력을 하면, 파일 검색 시 target파일은 제외된다.

 

위 작업은, Spring Tool Suite 4 (4.5.1 RELEASE) 버전에서 작성된 것이며,

버전 및 Tool 종류에 따라 다를 수 있습니다.

 

 

 

 

'Java > etc' 카테고리의 다른 글

[JAVA] HttpClient Rest API 생성  (1) 2025.06.25
[JAVA] Interger와 null 비교  (0) 2023.06.11

+ Recent posts