We are not able to get the JSon Output from the thirdparty api using ajax from AEM
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