Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.
SOLVED

We are not able to get the JSon Output from the thirdparty api using ajax from AEM

Avatar

Level 1

Hi Team,

     When we try access the third party API we are not getting the response from the request. And we started debugging that we are able to hit the same api directly from the browser and are able to the response but the same response we are not able to get it through the AEM servlet. 

  Can anyone please help me on this.

 

Here is the piece of code that I had used :

 

  
    protected void doGet( SlingHttpServletRequest request,  SlingHttpServletResponse response) throws ServletException, IOException {
        final Resource resource = request.getResource();
        final ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        StringBuffer jsonResponseData = new StringBuffer();
        String readLine = null;
        String newPath = appConstants.TNYTIMES_ENDPOINT.toString() + appConstants.TNYTIMES_BOOKS_CATEGORIES_API.toString()
                + appConstants.TNYTIMES_QUERYPARAMETER.toString()
                + appConstants.TNYTIMES_API_KEY_PARAMETER_KEY.toString()
                + appConstants.TNYTIMES_API_KEY_PARAMETER_VALUE.toString();
        URL url = new URL(newPath);
        HttpURLConnection connection = (HttpURLConnection) url
                .openConnection();
        connection.setRequestMethod("GET");
        connection.setReadTimeout(15 * 10000);
        connection.connect();
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while ((readLine = in.readLine()) != null) {
            uniqueBookList.add(readLine);
        }
        in.close();
        Iterator<String> itr = uniqueBookList.iterator();
        while (itr.hasNext()) {
            jsonResponseData.append(itr.next());
        }
        response.getWriter().write(jsonResponseData.toString());

    }

 


Here is the third party api: "https://api.nytimes.com/svc/books/v3/lists/names.json?api-key=y5GQJ5ljcgfpEZ4TpGRMnWb7RabGFPUB"

Here is the Ajax call :

 

$(document).ready(function() {
    console.log("testing");
    console.log("before calling Ajax");
    $.ajax({        
        url: "/bin/myaem65training/fetchbooks",
        type: 'GET',
        dataType: 'json',
        success: function(myresponse) {
            console.log("In the Success Method");
            $.each(myresponse.results,function(key, value){
                console.log(value["display_name"]);
            });
        },
        failure: function(myresponse) {
            console.log("In the Failure Method");
            CQ.Notification.notifyFromResponse(myresponse) ;
        }
    });
    
    console.log("after calling Ajax");

});

 

 

Here we are using the AEM Cloud for the development.

 

Thanks,

Pavan

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

@PavanKu2 

Try this code:

String newPath = appConstants.TNYTIMES_ENDPOINT.toString() + appConstants.TNYTIMES_BOOKS_CATEGORIES_API.toString()
                + appConstants.TNYTIMES_QUERYPARAMETER.toString()
                + appConstants.TNYTIMES_API_KEY_PARAMETER_KEY.toString()
                + appConstants.TNYTIMES_API_KEY_PARAMETER_VALUE.toString();

int timeout = 5;
RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(10000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpGet httpget = new HttpGet(newPath);
CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpget);
bufferedReader = new BufferedReader(new InputStreamReader(closeableHttpResponse.getEntity().getContent()));

StringBuilder result = new StringBuilder();
String line ;
while ((line = bufferedReader.readLine()) != null) {
    result.append(line);
}
com.google.gson.JsonParser jsonParser = new JsonParser();
com.google.gson.jsonObject = jsonParser.parse(result.toString()).getAsJsonObject();
mapper.writer().writeValue(response.getWriter(), jsonObject);

 

Please remember to close the objects like 

httpClient.close();
bufferedReader.close();

in the try/catch/finally block.

 

Hope this helps.

 

 

View solution in original post

4 Replies

Avatar

Level 2

Hi @PavanKu2 

 

I am not sure if I am getting your question, but it seems like you are trying to fetch a JSON webpage and store that into uniqueBookList. However you are reading it via readLine, that does not guarantee that readline gives you valid JSON object.

 

Instead you should use first store webpage body as text and the parse it using javax.JSON and then access it as you wish 

Avatar

Community Advisor

Hi @PavanKu2 

 

So It's a simple GET call to the third party API, right?

You can use HttpPost and HttpClient to call and get HttpResponse.

Let me know if that is what you want to achieve, I will share sample code snippet to make GET call from AEM Servlet.

Below blog will help you as well,

https://blogs.perficient.com/2019/01/23/how-to-test-apache-httpclient-in-the-context-of-aem/

 

Hope it helps

Avatar

Correct answer by
Community Advisor

@PavanKu2 

Try this code:

String newPath = appConstants.TNYTIMES_ENDPOINT.toString() + appConstants.TNYTIMES_BOOKS_CATEGORIES_API.toString()
                + appConstants.TNYTIMES_QUERYPARAMETER.toString()
                + appConstants.TNYTIMES_API_KEY_PARAMETER_KEY.toString()
                + appConstants.TNYTIMES_API_KEY_PARAMETER_VALUE.toString();

int timeout = 5;
RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setConnectionRequestTimeout(timeout * 1000).setSocketTimeout(10000).build();
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
HttpGet httpget = new HttpGet(newPath);
CloseableHttpResponse closeableHttpResponse = httpClient.execute(httpget);
bufferedReader = new BufferedReader(new InputStreamReader(closeableHttpResponse.getEntity().getContent()));

StringBuilder result = new StringBuilder();
String line ;
while ((line = bufferedReader.readLine()) != null) {
    result.append(line);
}
com.google.gson.JsonParser jsonParser = new JsonParser();
com.google.gson.jsonObject = jsonParser.parse(result.toString()).getAsJsonObject();
mapper.writer().writeValue(response.getWriter(), jsonObject);

 

Please remember to close the objects like 

httpClient.close();
bufferedReader.close();

in the try/catch/finally block.

 

Hope this helps.