-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDevoteMeApiClient.java
More file actions
41 lines (34 loc) · 1.35 KB
/
DevoteMeApiClient.java
File metadata and controls
41 lines (34 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.devoteme.minecraft.api;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class DevoteMeApiClient {
private final HttpClient client = HttpClient.newHttpClient();
private final String baseUrl;
private final String apiKeyOrNull;
public DevoteMeApiClient(String baseUrl, String apiKey) {
String b = baseUrl == null ? "" : baseUrl.trim();
this.baseUrl = b.endsWith("/") ? b.substring(0, b.length() - 1) : b;
this.apiKeyOrNull = (apiKey == null || apiKey.isBlank()) ? null : apiKey.trim();
}
public CompletableFuture<String> getJson(String path) {
if (baseUrl.isEmpty()) {
return CompletableFuture.failedFuture(new IllegalStateException("devoteme.baseUrl is empty"));
}
HttpRequest.Builder req = HttpRequest.newBuilder()
.uri(URI.create(baseUrl + path))
.GET()
.header("Accept", "application/json");
if (apiKeyOrNull != null) {
req.header("x-access-token", apiKeyOrNull);
}
return client.sendAsync(req.build(), HttpResponse.BodyHandlers.ofString())
.thenApply(resp -> {
int sc = resp.statusCode();
if (sc < 200 || sc >= 300) throw new RuntimeException("HTTP " + sc + " for " + path);
return resp.body();
});
}
}