260720_01_ENH: API multipart 호출 post put 추가
This commit is contained in:
@@ -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<String, String> headers,
|
||||
List<ExternalApiMultipartPart> parts) {
|
||||
return sendMultipart("POST", url, headers, parts);
|
||||
}
|
||||
|
||||
public ExternalApiResponse putMultipart(String url, Map<String, String> headers,
|
||||
List<ExternalApiMultipartPart> parts) {
|
||||
return sendMultipart("PUT", url, headers, parts);
|
||||
}
|
||||
|
||||
private ExternalApiResponse send(String method, String url, Map<String, String> 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<String> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private ExternalApiResponse sendMultipart(String method, String url, Map<String, String> headers,
|
||||
List<ExternalApiMultipartPart> 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<String> 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<ExternalApiMultipartPart> 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<String, String> 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user