|
| 1 | +package ${packageName}; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.type.TypeReference; |
| 4 | +import com.fasterxml.jackson.databind.DeserializationFeature; |
| 5 | +import com.fasterxml.jackson.databind.ObjectMapper; |
| 6 | +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; |
| 7 | + |
| 8 | +import java.io.IOException; |
| 9 | +import java.net.URI; |
| 10 | +import java.net.URLEncoder; |
| 11 | +import java.net.http.HttpClient; |
| 12 | +import java.net.http.HttpRequest; |
| 13 | +import java.net.http.HttpResponse; |
| 14 | +import java.nio.charset.StandardCharsets; |
| 15 | +import java.time.Duration; |
| 16 | +import java.util.HashMap; |
| 17 | +import java.util.Map; |
| 18 | +import java.util.StringJoiner; |
| 19 | + |
| 20 | +public class ApiClient { |
| 21 | + private final String baseUrl; |
| 22 | + private final HttpClient httpClient; |
| 23 | + private final ObjectMapper objectMapper; |
| 24 | + private final Map<String, String> defaultHeaders = new HashMap<>(); |
| 25 | + |
| 26 | + public ApiClient(String baseUrl) { |
| 27 | + this(baseUrl, HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build()); |
| 28 | + } |
| 29 | + |
| 30 | + public ApiClient(String baseUrl, HttpClient httpClient) { |
| 31 | + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl; |
| 32 | + this.httpClient = httpClient; |
| 33 | + this.objectMapper = new ObjectMapper() |
| 34 | + .registerModule(new JavaTimeModule()) |
| 35 | + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); |
| 36 | + this.defaultHeaders.put("Content-Type", "application/json"); |
| 37 | + this.defaultHeaders.put("Accept", "application/json"); |
| 38 | + } |
| 39 | + |
| 40 | + public ApiClient setDefaultHeader(String name, String value) { |
| 41 | + this.defaultHeaders.put(name, value); |
| 42 | + return this; |
| 43 | + } |
| 44 | + |
| 45 | + public <T> T get(String path, Map<String, Object> query, TypeReference<T> typeRef) { |
| 46 | + HttpRequest request = baseRequest("GET", buildUrl(path, query), null); |
| 47 | + return send(request, typeRef); |
| 48 | + } |
| 49 | + |
| 50 | + public <T> T post(String path, Object body, TypeReference<T> typeRef) { |
| 51 | + HttpRequest request = baseRequest("POST", buildUrl(path, null), serialize(body)); |
| 52 | + return send(request, typeRef); |
| 53 | + } |
| 54 | + |
| 55 | + public <T> T put(String path, Object body, TypeReference<T> typeRef) { |
| 56 | + HttpRequest request = baseRequest("PUT", buildUrl(path, null), serialize(body)); |
| 57 | + return send(request, typeRef); |
| 58 | + } |
| 59 | + |
| 60 | + public <T> T patch(String path, Object body, TypeReference<T> typeRef) { |
| 61 | + HttpRequest request = baseRequest("PATCH", buildUrl(path, null), serialize(body)); |
| 62 | + return send(request, typeRef); |
| 63 | + } |
| 64 | + |
| 65 | + public void delete(String path) { |
| 66 | + HttpRequest request = baseRequest("DELETE", buildUrl(path, null), null); |
| 67 | + send(request, new TypeReference<Void>() {}); |
| 68 | + } |
| 69 | + |
| 70 | + private HttpRequest baseRequest(String method, String url, String body) { |
| 71 | + HttpRequest.Builder builder = HttpRequest.newBuilder() |
| 72 | + .uri(URI.create(url)) |
| 73 | + .timeout(Duration.ofSeconds(30)); |
| 74 | + |
| 75 | + for (Map.Entry<String, String> e : defaultHeaders.entrySet()) { |
| 76 | + builder.header(e.getKey(), e.getValue()); |
| 77 | + } |
| 78 | + |
| 79 | + if ("GET".equals(method) || body == null) { |
| 80 | + builder.method(method, HttpRequest.BodyPublishers.noBody()); |
| 81 | + } else { |
| 82 | + builder.method(method, HttpRequest.BodyPublishers.ofString(body)); |
| 83 | + } |
| 84 | + return builder.build(); |
| 85 | + } |
| 86 | + |
| 87 | + private String buildUrl(String path, Map<String, Object> query) { |
| 88 | + StringBuilder sb = new StringBuilder(); |
| 89 | + sb.append(baseUrl); |
| 90 | + if (!path.startsWith("/")) sb.append('/'); |
| 91 | + sb.append(path); |
| 92 | + if (query != null && !query.isEmpty()) { |
| 93 | + StringJoiner joiner = new StringJoiner("&"); |
| 94 | + for (Map.Entry<String, Object> e : query.entrySet()) { |
| 95 | + if (e.getValue() == null) continue; |
| 96 | + joiner.add(encode(e.getKey()) + "=" + encode(String.valueOf(e.getValue()))); |
| 97 | + } |
| 98 | + String qs = joiner.toString(); |
| 99 | + if (!qs.isEmpty()) sb.append('?').append(qs); |
| 100 | + } |
| 101 | + return sb.toString(); |
| 102 | + } |
| 103 | + |
| 104 | + private String encode(String s) { |
| 105 | + return URLEncoder.encode(s, StandardCharsets.UTF_8); |
| 106 | + } |
| 107 | + |
| 108 | + private String serialize(Object value) { |
| 109 | + try { |
| 110 | + return objectMapper.writeValueAsString(value == null ? new HashMap<>() : value); |
| 111 | + } catch (IOException e) { |
| 112 | + throw new RuntimeException(e); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + private <T> T send(HttpRequest request, TypeReference<T> typeRef) { |
| 117 | + try { |
| 118 | + HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); |
| 119 | + int code = response.statusCode(); |
| 120 | + String body = response.body(); |
| 121 | + if (code >= 200 && code < 300) { |
| 122 | + if (typeRef.getType().getTypeName().equals(Void.class.getTypeName())) { |
| 123 | + return null; |
| 124 | + } |
| 125 | + return objectMapper.readValue(body, typeRef); |
| 126 | + } |
| 127 | + throw new ApiException(code, "HTTP " + code, body); |
| 128 | + } catch (IOException | InterruptedException e) { |
| 129 | + throw new RuntimeException(e); |
| 130 | + } |
| 131 | + } |
| 132 | +} |
| 133 | + |
| 134 | + |
0 commit comments