|
| 1 | +package dev.resms.core.net.impl; |
| 2 | + |
| 3 | +import dev.resms.core.net.AbstractHttpResponse; |
| 4 | +import dev.resms.core.net.HttpMethod; |
| 5 | +import dev.resms.core.net.IHttpClient; |
| 6 | +import java.io.IOException; |
| 7 | +import okhttp3.MediaType; |
| 8 | +import okhttp3.OkHttpClient; |
| 9 | +import okhttp3.Request; |
| 10 | +import okhttp3.RequestBody; |
| 11 | +import okhttp3.Response; |
| 12 | + |
| 13 | +/** |
| 14 | + * An implementation of the {@link IHttpClient} interface for performing HTTP requests. This |
| 15 | + * implementation uses the OkHttp library for handling HTTP communication. |
| 16 | + */ |
| 17 | +public class HttpClient implements IHttpClient<Response> { |
| 18 | + |
| 19 | + /** The base URL for the API. */ |
| 20 | + public static final String BASE_API = "https://api.resms.dev/"; |
| 21 | + |
| 22 | + /** The OkHttpClient instance for handling HTTP requests. */ |
| 23 | + private final OkHttpClient httpClient; |
| 24 | + |
| 25 | + /** Constructs an instance of the HttpClient. */ |
| 26 | + public HttpClient() { |
| 27 | + this.httpClient = new OkHttpClient(); |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Performs an HTTP request with the specified path, HTTP method, and payload. |
| 32 | + * |
| 33 | + * @param path The path or endpoint of the request. |
| 34 | + * @param apiKey The API Key used to authenticate the request. |
| 35 | + * @param method The HTTP method (GET, POST, PUT, DELETE, etc.). |
| 36 | + * @param payload The payload or data to send with the request. |
| 37 | + * @return An {@link AbstractHttpResponse} representing the response from the server. |
| 38 | + */ |
| 39 | + @Override |
| 40 | + public AbstractHttpResponse<Response> perform( |
| 41 | + final String path, final String apiKey, final HttpMethod method, final String payload) { |
| 42 | + |
| 43 | + RequestBody requestBody = null; |
| 44 | + if (payload != null) { |
| 45 | + requestBody = RequestBody.create(payload, MediaType.get("application/json")); |
| 46 | + } |
| 47 | + |
| 48 | + Request request = |
| 49 | + new Request.Builder() |
| 50 | + .url(BASE_API + path) |
| 51 | + .addHeader("Accept", "application/json") |
| 52 | + .addHeader("X-Api-Key", apiKey) |
| 53 | + .method(method.name(), requestBody) |
| 54 | + .build(); |
| 55 | + |
| 56 | + try { |
| 57 | + Response response = httpClient.newCall(request).execute(); |
| 58 | + return new AbstractHttpResponse( |
| 59 | + response.code(), response.body().string(), response.isSuccessful()); |
| 60 | + } catch (IOException e) { |
| 61 | + throw new RuntimeException(e); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments