not able to hit the URL in this code can someone suggest the inputs
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public String fetchApiData(String apiUrl) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(apiUrl);
CloseableHttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() == 200) {
return EntityUtils.toString(response.getEntity());
} else {
throw new IOException("Failed to fetch API data");
}
}
Hi @Raju_AEM1 ,
I would suggest using org.apache.http.osgi.services.HttpClientBuilderFactory. This is a best practice to manage HTTP Clients creation inside AEM env.
private Optional<String> fetchApiData(String apiUrl) {
try (CloseableHttpClient httpClient = httpClientBuilderFactory.newBuilder()
.setDefaultRequestConfig(requestConfig)
.build()) {
HttpGet getRequest = new HttpGet(apiUrl);
CloseableHttpResponse response = httpClient.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK || response.getEntity() == null) {
return Optional.empty();
}
return Optional.ofNullable(IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
} catch (IOException e) {
LOG.error("Exception retrieving json results: {}", e.getMessage(), e);
}
return Optional.empty();
}
Best regards,
Kostiantyn Diachenko.
hi @Raju_AEM1, here some check to do:
try {
// Execute HTTP request
} catch (ConnectException e) {
logger.error("Could not connect to the server", e);
} catch (SSLException e) {
logger.error("SSL connection error", e);
} catch (IOException e) {
logger.error("Other I/O errors", e);
}
HttpGet httpGet = new HttpGet(apiUrl); httpGet.setHeader("Authorization", "Bearer your_token"); httpGet.setHeader("Content-Type", "application/json");
HttpHost proxy = new HttpHost("proxy.example.com", 8080); RequestConfig config = RequestConfig.custom().setProxy(proxy).build(); httpGet.setConfig(config);
RequestConfig config = RequestConfig.custom() .setConnectTimeout(5000) // 5 seconds .setSocketTimeout(10000) // 10 seconds .build(); httpGet.setConfig(config);
try (CloseableHttpClient httpClient = HttpClients.createDefault()) { // Use httpClient here } catch (Exception e) { // Handle exceptions }
As a general rule, I recommend creating a dedicated HTTP client that can be injected into other classes to centralize project logic (for example, timeout values). You can find an example in my repository, aem-cdn-cache-invalidator, where the OSGI service `HttpClientServiceImpl.java` includes the following configuration fields:
Views
Replies
Total Likes
Views
Like
Replies
Views
Likes
Replies