Expand my Community achievements bar.

consuming third party apis through osgi service

Avatar

Level 1

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");
    }
}
2 Replies

Avatar

Community Advisor

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.

 

 

Avatar

Level 7

hi @Raju_AEM1, here some check to do:

  • Ensure that the apiUrl you're using is correct. A typo or incorrect path can lead to failed requests.
  • Ensure that your machine and network allow connections to the API's domain and port. Look for any firewall rules that might be blocking outgoing connections to the API's endpoint.
  • Modify your code to catch specific exceptions like ConnectException or SSLHandshakeException to get detailed error information.
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);
}
  • If the API requires specific headers (e.g., AuthorizationContent-Type), include them in your request.
    HttpGet httpGet = new HttpGet(apiUrl);
    httpGet.setHeader("Authorization", "Bearer your_token");
    httpGet.setHeader("Content-Type", "application/json");
  • If you're behind a proxy, configure the HTTP client to use the proxy settings.
    HttpHost proxy = new HttpHost("proxy.example.com", 8080);
    RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
    httpGet.setConfig(config);
  • If the server is slow in responding, set appropriate connection and socket timeouts.
    RequestConfig config = RequestConfig.custom()
        .setConnectTimeout(5000)    // 5 seconds
        .setSocketTimeout(10000)    // 10 seconds
        .build();
    httpGet.setConfig(config);
  • Ensure that the CloseableHttpClient and CloseableHttpResponse are properly closed to prevent resource leaks.
    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:

  • HTTP Connection Timeout: the value in milliseconds that determines how long the HTTP client will wait for a connection to be established
  • HTTP Connection Request Timeout: the value in milliseconds that determines how long the HTTP client will wait for a connection to be available from the connection pool
  • HTTP Socket Timeout: the value in milliseconds that determines how long the HTTP client will wait for data to be received or sent
  • HTTP Max Total Connections: the maximum number of connections that the HTTP client can open
  • HTTP Max Connections per Route: the maximum number of connections that the HTTP client can open for a given route