From 0013636a8822d30c279f4072b473cecdc1a58b93 Mon Sep 17 00:00:00 2001 From: kric_jspark Date: Mon, 20 Jul 2026 11:38:04 +0900 Subject: [PATCH] =?UTF-8?q?260720=5F01=5FENH:=20API=20multipart=20?= =?UTF-8?q?=ED=98=B8=EC=B6=9C=20post=20put=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Agents.md | 9 ++ README.md | 16 +++ .../feature/http/ExternalApiClient.java | 122 +++++++++++++++--- .../http/ExternalApiMultipartPart.java | 66 ++++++++++ 4 files changed, 192 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/kri/common/feature/http/ExternalApiMultipartPart.java diff --git a/Agents.md b/Agents.md index c4ecc7f..32daeb9 100644 --- a/Agents.md +++ b/Agents.md @@ -164,6 +164,15 @@ Behavior: - Requires `RedisTemplate` class and `RedisConnectionFactory` bean. - Registers `RedisQueueHelper`. +### External API Client + +- Public classes: `ExternalApiClient`, `ExternalApiResponse`, `ExternalApiMultipartPart` +- JDK `HttpClient` based lightweight HTTP client. +- Supports `GET`, `DELETE`, `POST`, `PUT`, `PATCH` with `String` request bodies. +- Supports multipart uploads through `postMultipart` and `putMultipart`. +- Multipart requests ignore caller-supplied `Content-Type` and generate `multipart/form-data` with the required boundary. +- Responses are returned as `String` body via `ExternalApiResponse`. + ### HTTP Bypass - Public classes: `BypassClient`, `BypassRequest`, `BypassResponse`, `BypassContext`, `BypassForwardOptions`, `BypassRequestCustomizer`, `BypassResponseCustomizer` diff --git a/README.md b/README.md index 7a3f499..7adc360 100644 --- a/README.md +++ b/README.md @@ -173,6 +173,20 @@ ExternalApiClient client = new ExternalApiClient(); ExternalApiResponse res = client.post(url, headers, jsonBody); ``` +`ExternalApiMultipartPart`를 사용해 `multipart/form-data` 업로드를 전송할 수 있습니다. + +```java +List parts = List.of( + ExternalApiMultipartPart.formField("serviceCode", "demo"), + ExternalApiMultipartPart.file("file", "sample.txt", "text/plain", fileBytes) +); + +ExternalApiResponse res = client.postMultipart(url, headers, parts); +``` + +multipart 요청에서는 전달한 headers의 `Content-Type` 값을 무시하고, 필요한 boundary를 포함한 +`Content-Type: multipart/form-data; boundary=...` 값을 자동 생성합니다. + 지원 메서드: - `get` @@ -180,6 +194,8 @@ ExternalApiResponse res = client.post(url, headers, jsonBody); - `post` - `put` - `patch` +- `postMultipart` +- `putMultipart` 응답은 `statusCode`, `headers`, `body`를 제공합니다. diff --git a/src/main/java/com/kri/common/feature/http/ExternalApiClient.java b/src/main/java/com/kri/common/feature/http/ExternalApiClient.java index 265331b..eb48986 100644 --- a/src/main/java/com/kri/common/feature/http/ExternalApiClient.java +++ b/src/main/java/com/kri/common/feature/http/ExternalApiClient.java @@ -1,41 +1,39 @@ package com.kri.common.feature.http; +import java.io.ByteArrayOutputStream; 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.nio.charset.StandardCharsets; import java.time.Duration; +import java.util.List; import java.util.Map; +import java.util.UUID; /** - * 간단한 외부 API 통신 모듈. - url, 추가 헤더, body를 받아 호출합니다. - GET, POST, PUT, PATCH, DELETE 메서드를 제공합니다. - - * body는 문자열(JSON 등) 기준입니다. + * Lightweight HTTP client based on JDK HttpClient. */ public class ExternalApiClient { + private static final String CRLF = "\r\n"; + private final HttpClient httpClient; private final Duration requestTimeout; - /** - * 기본 생성자 (커넥션 풀/타임아웃 기본값 세팅) - */ public ExternalApiClient() { this(HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(10)) .build(), Duration.ofSeconds(30)); } - /** - * 사용자 지정 HttpClient/요청 타임아웃으로 생성 - */ public ExternalApiClient(HttpClient httpClient, Duration requestTimeout) { this.httpClient = httpClient; this.requestTimeout = requestTimeout == null ? Duration.ofSeconds(30) : requestTimeout; } private static HttpRequest.BodyPublisher buildBodyPublisher(String method, String body) { - // GET/DELETE 등 body 없는 메서드는 noBody 사용 if (body == null || body.isEmpty()) { return switch (method) { case "POST", "PUT", "PATCH" -> HttpRequest.BodyPublishers.ofString(""); @@ -65,6 +63,16 @@ public class ExternalApiClient { return send("PATCH", url, headers, body); } + public ExternalApiResponse postMultipart(String url, Map headers, + List parts) { + return sendMultipart("POST", url, headers, parts); + } + + public ExternalApiResponse putMultipart(String url, Map headers, + List parts) { + return sendMultipart("PUT", url, headers, parts); + } + private ExternalApiResponse send(String method, String url, Map headers, String body) { try { @@ -73,16 +81,8 @@ public class ExternalApiClient { .timeout(requestTimeout) .method(method, buildBodyPublisher(method, body)); - // 추가 헤더 설정 - if (headers != null) { - headers.forEach((k, v) -> { - if (k != null && v != null) { - builder.header(k, v); - } - }); - } + applyHeaders(builder, headers, false); - // body가 있고 Content-Type이 없다면 기본 application/json if (body != null && (headers == null || !headers.keySet().stream() .map(String::toLowerCase).anyMatch("content-type"::equals))) { builder.header("Content-Type", "application/json; charset=utf-8"); @@ -92,11 +92,91 @@ public class ExternalApiClient { HttpResponse resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body()); } catch (IOException | InterruptedException e) { - // 인터럽트 복원 if (e instanceof InterruptedException) { Thread.currentThread().interrupt(); } - throw new RuntimeException("External API 호출 중 오류가 발생했습니다: " + e.getMessage(), e); + throw new RuntimeException("External API call failed: " + e.getMessage(), e); } } -} \ No newline at end of file + + private ExternalApiResponse sendMultipart(String method, String url, Map headers, + List parts) { + try { + String boundary = "----KriCommonBoundary" + UUID.randomUUID().toString().replace("-", ""); + byte[] body = buildMultipartBody(parts, boundary); + + HttpRequest.Builder builder = HttpRequest.newBuilder() + .uri(URI.create(url)) + .timeout(requestTimeout) + .method(method, HttpRequest.BodyPublishers.ofByteArray(body)); + + applyHeaders(builder, headers, true); + builder.header("Content-Type", "multipart/form-data; boundary=" + boundary); + + HttpRequest request = builder.build(); + HttpResponse resp = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + return ExternalApiResponse.of(resp.statusCode(), resp.headers(), resp.body()); + } catch (IOException | InterruptedException e) { + if (e instanceof InterruptedException) { + Thread.currentThread().interrupt(); + } + throw new RuntimeException("External API call failed: " + e.getMessage(), e); + } + } + + private static byte[] buildMultipartBody(List parts, String boundary) + throws IOException { + if (parts == null || parts.isEmpty()) { + throw new IllegalArgumentException("parts must not be empty"); + } + + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (ExternalApiMultipartPart part : parts) { + if (part == null) { + throw new IllegalArgumentException("parts must not contain null"); + } + + writeAscii(out, "--" + boundary + CRLF); + writeAscii(out, "Content-Disposition: form-data; name=\"" + headerValue(part.getName()) + "\""); + if (part.getFilename() != null) { + writeAscii(out, "; filename=\"" + headerValue(part.getFilename()) + "\""); + } + writeAscii(out, CRLF); + if (part.getContentType() != null && !part.getContentType().isBlank()) { + writeAscii(out, "Content-Type: " + safeHeader(part.getContentType()) + CRLF); + } + writeAscii(out, CRLF); + out.write(part.content()); + writeAscii(out, CRLF); + } + writeAscii(out, "--" + boundary + "--" + CRLF); + return out.toByteArray(); + } + + private static void applyHeaders(HttpRequest.Builder builder, Map headers, + boolean ignoreContentType) { + if (headers == null) { + return; + } + headers.forEach((k, v) -> { + if (k != null && v != null && !(ignoreContentType && "content-type".equalsIgnoreCase(k))) { + builder.header(k, v); + } + }); + } + + private static void writeAscii(ByteArrayOutputStream out, String value) throws IOException { + out.write(value.getBytes(StandardCharsets.US_ASCII)); + } + + private static String headerValue(String value) { + return safeHeader(value).replace("\\", "\\\\").replace("\"", "\\\""); + } + + private static String safeHeader(String value) { + if (value.indexOf('\r') >= 0 || value.indexOf('\n') >= 0) { + throw new IllegalArgumentException("multipart header values must not contain CR/LF"); + } + return value; + } +} diff --git a/src/main/java/com/kri/common/feature/http/ExternalApiMultipartPart.java b/src/main/java/com/kri/common/feature/http/ExternalApiMultipartPart.java new file mode 100644 index 0000000..58f5aa0 --- /dev/null +++ b/src/main/java/com/kri/common/feature/http/ExternalApiMultipartPart.java @@ -0,0 +1,66 @@ +package com.kri.common.feature.http; + +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Objects; + +/** + * Part descriptor for {@link ExternalApiClient} multipart/form-data requests. + */ +public final class ExternalApiMultipartPart { + + private final String name; + private final String filename; + private final String contentType; + private final byte[] content; + + private ExternalApiMultipartPart(String name, String filename, String contentType, + byte[] content) { + this.name = requireText(name, "name"); + this.filename = filename; + this.contentType = contentType; + this.content = content == null ? new byte[0] : Arrays.copyOf(content, content.length); + } + + public static ExternalApiMultipartPart formField(String name, String value) { + byte[] content = value == null ? new byte[0] : value.getBytes(StandardCharsets.UTF_8); + return new ExternalApiMultipartPart(name, null, null, content); + } + + public static ExternalApiMultipartPart file(String name, String filename, String contentType, + byte[] content) { + return new ExternalApiMultipartPart( + name, + requireText(filename, "filename"), + contentType == null || contentType.isBlank() ? "application/octet-stream" : contentType, + content); + } + + public String getName() { + return name; + } + + public String getFilename() { + return filename; + } + + public String getContentType() { + return contentType; + } + + public byte[] getContent() { + return Arrays.copyOf(content, content.length); + } + + byte[] content() { + return content; + } + + private static String requireText(String value, String fieldName) { + Objects.requireNonNull(value, fieldName + " must not be null"); + if (value.isBlank()) { + throw new IllegalArgumentException(fieldName + " must not be blank"); + } + return value; + } +}