Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

Sample example to connect to 3rd party REST API in AEM on custom submit action / on button click as developer ?

Avatar

Level 2

I have created a servlet and have implemented the http connection using HttpsURLConnection but unable  to connect the same to post.Post.jsp. I had created an object of that and tried implementing the function but can find not hits to the url in browser network.Kindly share an example or Sample example to connect to 3rd party REST API in AEM on custom submit action / on button click as developer ?

2 Accepted Solutions

Avatar

Correct answer by
Employee Advisor

You will need to write a custom submit action as explained in the article that  I sent you. In the custom submit post.jsp you will add the following code

com.adobe.aemds.guide.utils.GuideSubmitUtils.setForwardPath(slingRequest,"/bin/storeafsubmission",null,null);

 

Repalce the /bin/storeafsubmission with your path(/bin/demo/httpcall) 

View solution in original post

Avatar

Correct answer by
Employee Advisor

your servlet is expecting a GET call. You will need to change it to make it to POST servlet. For that you need to extend SlingAllMethodsServlet

View solution in original post

10 Replies

Avatar

Employee Advisor

so you have created a servlet and want to call the servlet on form submission?

Avatar

Level 2

yes exactly ...

HttpServlet.java

 

package com.mysite.core.servlets;

import javax.servlet.Servlet;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.framework.Constants;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import java.util.logging.FileHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mysite.core.services.HttpService;

/**
 * @author Anirudh Sharma
 *
 * This method makes an HTTP call and read the value from the JSON webservice via an OSGi configuration
 *
 */
@Component(service = Servlet.class, property = { Constants.SERVICE_DESCRIPTION + "=HTTP servlet",
        "sling.servlet.methods=" + HttpConstants.METHOD_GET, "sling.servlet.paths=" + "/bin/demo/httpcall" })
public class HttpServlet extends SlingSafeMethodsServlet {
   
    /**
     * Generated serialVersionUid
     */
    private static final long serialVersionUID = -2014397651676211439L;
   
    /**
     * Logger
     */
    private static final Logger log = LoggerFactory.getLogger(HttpServlet.class);
   
    @Reference
    private HttpService httpService;
   
    /**
     * Overridden doGet() method
     */
    @Override
    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
       
        try {
       
        String jsonResponse = httpService.makeHttpCall();
       
        /**
         * Printing the json response on the browser
         */
        response.getWriter().println(jsonResponse);
       
        } catch (Exception e) {
           
            log.error(e.getMessage(), e);
        }
    }

}
 
 
 
HttpServiceImpl.java
 
package com.mysite.core.services.impl;

import java.util.logging.FileHandler;

import org.apache.log4j.PropertyConfigurator;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.metatype.annotations.Designate;

//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;

import java.util.logging.FileHandler;
import java.util.logging.Logger;

import com.mysite.core.services.HttpConfiguration;
import com.mysite.core.services.HttpService;
import com.mysite.core.utils.Network;

/**
 * @author Anirudh Sharma
 *
 * Implementation class of HttpService interface and this class reads values from the OSGi configuration as well
 */
@Component(service = HttpService.class, immediate = true)
@Designate(ocd = HttpConfiguration.class)
public class HttpServiceImpl implements HttpService {

//public static Logger logger = null;

    /**
     * Logger
     */
    //private static final Logger log = LoggerFactory.getLogger(HttpServiceImpl.class);

    /**
     * Instance of the OSGi configuration class
     */
    private HttpConfiguration configuration;

    @Activate
    protected void activate(HttpConfiguration configuration) {
        this.configuration = configuration;
    }

    /**
     * Overridden method of the HttpService
     */
    @Override
    public String makeHttpCall() throws Exception {

        boolean append = true;
        FileHandler handler = new FileHandler("default.log", append);
 
        Logger log = Logger.getLogger("com.mysite.core.services.impl");
        log.addHandler(handler);
        log.info("----------< Reading the config values >----------");
       
        try {

            /**
             * Reading values from the configuration
             */
            boolean enable = true;
            String protocol = "https";
            String server = "jsonplaceholder.typicode.com";
            String endpoint = "todos";

            /**
             * Constructing the URL
             */
            String url = protocol + "://" + server + "/" + endpoint;

            /**
             * Make HTTP call only if "enable" is true
             */
            if (enable) {
                /**
                 * Making the actual HTTP call
                 */
                String response = Network.readJson(url);

                /**
                 * Printing the response in the logs
                 */
                log.info("----------< JSON response from the webservice is >----------");
                log.info(response);
                System.out.println("response");
                return response;
               
            } else {
               
                log.info("----------< Configuration is not enabled >----------");
               
                return "Configuration not enabled";
            }

        } catch (Exception e) {

            //log.error(e.getMessage(), e);
           
            return "Error occurred" + e.getMessage();
        }
    }

}
 
Kindly suggest how can i call the  makeHttpCall() in post.Post.jsp

 

Avatar

Level 2

As I am a beginner kindly let me know if there is any other possibility of doing rest api call directly in post.Post.jsp

Avatar

Correct answer by
Employee Advisor

your servlet is expecting a GET call. You will need to change it to make it to POST servlet. For that you need to extend SlingAllMethodsServlet

Avatar

Employee Advisor

This is one way of doing it

https://experienceleague.adobe.com/docs/experience-manager-learn/forms/adaptive-forms/custom-submit-...

 

or you can do it this way

https://experienceleague.adobe.com/docs/experience-manager-learn/forms/handling-af-form-submissions/...

 

In the above example, it is submitting to external end point, but you can submit to your servlet running in AEM

Avatar

Correct answer by
Employee Advisor

You will need to write a custom submit action as explained in the article that  I sent you. In the custom submit post.jsp you will add the following code

com.adobe.aemds.guide.utils.GuideSubmitUtils.setForwardPath(slingRequest,"/bin/storeafsubmission",null,null);

 

Repalce the /bin/storeafsubmission with your path(/bin/demo/httpcall) 

Avatar

Level 2

Appreciate your quick reply !!!.. 

 

Will try out the same

Avatar

Community Advisor

Add below code in post.POST.jsp file while creating custom submit action.

"/bin/storeafsubmission" this is my servlet path.

This code works for me in aem 6.4 version

 

<%@include file="/libs/fd/af/components/guidesglobal.jsp"%>
<%@include file="/libs/foundation/global.jsp"%>

<%@ page import="org.apache.sling.api.request.RequestParameter,
com.day.cq.wcm.api.WCMMode,
com.day.cq.wcm.foundation.forms.FormsHelper,
org.apache.sling.api.resource.ResourceUtil,
org.apache.sling.api.resource.ValueMap,
com.adobe.forms.common.submitutils.CustomParameterRequest,
com.adobe.aemds.guide.utils.*" %>

<%@ page import="org.apache.sling.api.request.RequestParameter,
com.day.cq.wcm.api.WCMMode" %>

<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0"%>
<%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0"%>

<cq:defineObjects/>
<sling:defineObjects/>
<%@page session="false" %>
<%

com.adobe.aemds.guide.utils.GuideSubmitUtils.setForwardPath(slingRequest,"/bin/storeafsubmission",null,null);

%>

 

Links to create custom submit actions:

https://experienceleague.adobe.com/docs/experience-manager-learn/forms/adaptive-forms/custom-submit-...

Avatar

Employee Advisor

 


package com.aem.core.servlets; import com.aem.core.utils.Constants; import com.day.cq.wcm.api.Page; import com.day.cq.wcm.api.PageManager; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.SlingHttpServletResponse; import org.apache.sling.api.request.RequestParameter; import org.apache.sling.api.resource.ResourceResolver; import org.apache.sling.api.servlets.HttpConstants; import org.apache.sling.api.servlets.SlingAllMethodsServlet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.osgi.service.component.annotations.Component; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.Servlet; import javax.servlet.ServletException; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.List; import static org.apache.sling.api.servlets.ServletResolverConstants.*; @Component( service= {Servlet.class}, property={ "sling.servlet.methods="+ HttpConstants.METHOD_GET, SLING_SERVLET_METHODS+"="+HttpConstants.METHOD_POST, "sling.servlet.resourceTypes="+ "aem/components/structure/test-home", SLING_SERVLET_PATHS+"="+"/test/r5servlet", "sling.servlet.selectors=" + "test", "sling.servlet.selectors=" + "ds", SLING_SERVLET_EXTENSIONS+"="+"xml", "sling.servlet.extensions"+"="+"txt" }) public class Test extends SlingAllMethodsServlet { @Override protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException { final ResourceResolver resourceResolver = req.getResourceResolver(); String reqSelectors="SELECTORS => "; String reqExtension=req.getRequestPathInfo().getExtension(); try { String[] selectors=req.getRequestPathInfo().getSelectors(); for(String selector : selectors){ reqSelectors=reqSelectors +" "+selector; } } catch (Exception e) { LOG.info("\n ERROR {} ", e.getMessage()); } resp.setContentType("application/json"); resp.getWriter().write(reqSelectors+ " # " +reqExtension); } @Override protected void doPost(SlingHttpServletRequest req, SlingHttpServletResponse resp) throws ServletException, IOException { try { LOG.info("\n ------------------------STARTED POST-------------------------"); List<RequestParameter> requestParameterList=req.getRequestParameterList(); for(RequestParameter requestParameter : requestParameterList){ LOG.info("\n ==PARAMETERS===> {} : {} ",requestParameter.getName(),requestParameter.getString()); } }catch (Exception e){ LOG.info("\n ERROR IN REQUEST {} ",e.getMessage()); } resp.getWriter().write("======FORM SUBMITTED========"); } }

 

@JADISH if you are beginner I would say rather than hit and trial go with the basic on how sling servlets resolves.

 

start from here

https://www.youtube.com/watch?v=ZAlR0nPdpSI

https://experienceleague.adobe.com/docs/experience-manager-learn/forms/creating-your-first-osgi-bund....

 

Here is a working java file for servlet:

 

Link to git: https://github.com/aemgeeks1212/aemgeeks