Files
Backend/src/main/java/cc/fascinated/common/WebRequest.java

63 lines
1.9 KiB
Java
Raw Normal View History

2024-04-10 07:43:38 +01:00
package cc.fascinated.common;
2024-04-10 09:30:35 +01:00
import cc.fascinated.exception.impl.RateLimitException;
2024-04-10 07:43:38 +01:00
import lombok.experimental.UtilityClass;
2024-04-10 09:30:35 +01:00
import org.springframework.http.HttpStatus;
2024-04-13 15:34:19 +01:00
import org.springframework.http.HttpStatusCode;
2024-04-10 07:43:38 +01:00
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestClient;
@UtilityClass
public class WebRequest {
/**
* The web client.
*/
2024-04-13 15:34:19 +01:00
private static final RestClient CLIENT;
static {
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setConnectTimeout(5000); // 5 seconds
CLIENT = RestClient.builder()
.requestFactory(requestFactory)
.build();
}
2024-04-10 07:43:38 +01:00
/**
* Gets a response from the given URL.
*
* @param url the url
* @return the response
* @param <T> the type of the response
*/
2024-04-10 09:32:56 +01:00
public static <T> T getAsEntity(String url, Class<T> clazz) throws RateLimitException {
2024-04-13 15:34:19 +01:00
ResponseEntity<T> profile = CLIENT.get()
.uri(url)
.retrieve()
.toEntity(clazz);
2024-04-10 07:43:38 +01:00
2024-04-13 15:34:19 +01:00
if (profile.getStatusCode().isError()) {
2024-04-10 07:43:38 +01:00
return null;
}
2024-04-13 15:34:19 +01:00
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);
2024-04-10 07:43:38 +01:00
}
}