add mojang api status endpoint
Some checks failed
Deploy App / docker (ubuntu-latest, 2.44.0, 17, 3.8.5) (push) Failing after 27s
Some checks failed
Deploy App / docker (ubuntu-latest, 2.44.0, 17, 3.8.5) (push) Failing after 27s
This commit is contained in:
@ -3,9 +3,9 @@ package cc.fascinated.common;
|
||||
import cc.fascinated.exception.impl.RateLimitException;
|
||||
import lombok.experimental.UtilityClass;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
||||
import org.springframework.web.client.HttpClientErrorException;
|
||||
import org.springframework.web.client.RestClient;
|
||||
|
||||
@UtilityClass
|
||||
@ -14,9 +14,15 @@ public class WebRequest {
|
||||
/**
|
||||
* The web client.
|
||||
*/
|
||||
private static final RestClient CLIENT = RestClient.builder()
|
||||
.requestFactory(new HttpComponentsClientHttpRequestFactory())
|
||||
.build();
|
||||
private static final RestClient CLIENT;
|
||||
|
||||
static {
|
||||
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
|
||||
requestFactory.setConnectTimeout(5000); // 5 seconds
|
||||
CLIENT = RestClient.builder()
|
||||
.requestFactory(requestFactory)
|
||||
.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a response from the given URL.
|
||||
@ -26,21 +32,31 @@ public class WebRequest {
|
||||
* @param <T> the type of the response
|
||||
*/
|
||||
public static <T> T getAsEntity(String url, Class<T> clazz) throws RateLimitException {
|
||||
try {
|
||||
ResponseEntity<T> profile = CLIENT.get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.toEntity(clazz);
|
||||
ResponseEntity<T> profile = CLIENT.get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.toEntity(clazz);
|
||||
|
||||
if (profile.getStatusCode().isError()) {
|
||||
return null;
|
||||
}
|
||||
if (profile.getStatusCode().isSameCodeAs(HttpStatus.TOO_MANY_REQUESTS)) {
|
||||
throw new RateLimitException("Rate limit reached");
|
||||
}
|
||||
return profile.getBody();
|
||||
} catch (HttpClientErrorException ex) {
|
||||
if (profile.getStatusCode().isError()) {
|
||||
return null;
|
||||
}
|
||||
if (profile.getStatusCode().isSameCodeAs(HttpStatus.TOO_MANY_REQUESTS)) {
|
||||
throw new RateLimitException("Rate limit reached");
|
||||
}
|
||||
return profile.getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a response from the given URL.
|
||||
*
|
||||
* @param url the url
|
||||
* @return the response
|
||||
*/
|
||||
public static ResponseEntity<?> getAndIgnoreErrors(String url) {
|
||||
return CLIENT.get()
|
||||
.uri(url)
|
||||
.retrieve()
|
||||
.onStatus(HttpStatusCode::isError, (request, response) -> {}) // Don't throw exceptions on error
|
||||
.toEntity(String.class);
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user