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-10 07:43:38 +01:00
|
|
|
import org.springframework.http.ResponseEntity;
|
|
|
|
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
|
|
|
|
import org.springframework.web.client.HttpClientErrorException;
|
|
|
|
import org.springframework.web.client.RestClient;
|
|
|
|
|
|
|
|
@UtilityClass
|
|
|
|
public class WebRequest {
|
|
|
|
|
|
|
|
/**
|
|
|
|
* The web client.
|
|
|
|
*/
|
|
|
|
private static final RestClient CLIENT = RestClient.builder()
|
|
|
|
.requestFactory(new HttpComponentsClientHttpRequestFactory())
|
|
|
|
.build();
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 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-10 07:43:38 +01:00
|
|
|
try {
|
|
|
|
ResponseEntity<T> profile = CLIENT.get()
|
|
|
|
.uri(url)
|
|
|
|
.retrieve()
|
|
|
|
.toEntity(clazz);
|
|
|
|
|
|
|
|
if (profile.getStatusCode().isError()) {
|
|
|
|
return null;
|
|
|
|
}
|
2024-04-10 09:30:35 +01:00
|
|
|
if (profile.getStatusCode().isSameCodeAs(HttpStatus.TOO_MANY_REQUESTS)) {
|
|
|
|
throw new RateLimitException("Rate limit reached");
|
|
|
|
}
|
2024-04-10 07:43:38 +01:00
|
|
|
return profile.getBody();
|
|
|
|
} catch (HttpClientErrorException ex) {
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|