Expand my Community achievements bar.

SOLVED

post call to rest api using parameters from AEM form

Avatar

Level 2

How to pass post parameters from a AEM form to REST 3rd party api and handle the parameters in servlet and using HttpsURLConnection

1 Accepted Solution

Avatar

Correct answer by
Employee Advisor

when your form is submitting to a servlet, write the following code in your servlet

Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements())
{
String paramName = params.nextElement();
System.out.println("The param Name is "+paramName);
String data = request.getParameter(paramName);System.out.println("The data  is "+data);
}

. You will get to see the parameters passed to your servlet. You can then process the data as needed 

View solution in original post

3 Replies

Avatar

Employee Advisor

when you submit your form to your REST endpoint the entire form data is available in the servlet. You can convert the input stream to w3c.org.Document and then parse the xml as per your needs

Avatar

Community Advisor

@JADISH I recently worked on similar kind of implementation and below code of snippet would be really helpful for you. This implementation is done through core AEM form container component. In your servlet, 

 

1. Get the form data through request.getRequestParameterMap .

2. removing all OOB form data like ":formstart", "_charset_", ":redirect", ":cq_csrf_token". You can also read  parameters through request.getParamter("Object") in case if it's handful.

3. Creating httpClient post object , pass all the form data as entity and execute the client object

 

 

import com.google.common.collect.ImmutableSet;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
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.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.api.servlets.HttpConstants;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.servlets.annotations.SlingServletResourceTypes;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.propertytypes.ServiceDescription;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.Servlet;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Component(service = { Servlet.class })
@SlingServletResourceTypes(
resourceTypes={
"<<Your resource type name>>",
},
methods= HttpConstants.METHOD_POST,
extensions="bin",
selectors="post")
@ServiceDescription("Handles submission of form to REST endpoint")
public class SubmitToRestServlet extends SlingAllMethodsServlet {

private static final Logger LOGGER = LoggerFactory.getLogger(SubmitToRestServlet.class);
private static final String AUTHORIZATION = "Authorization";
private static final String BEARER = "Bearer";

private static final String REST_FORM_ENDPOINT_URL = "restServiceEndPointUrl";
private static final String REDIRECT_PROP = "redirect";

 

private static final Set<String> INTERNAL_PARAMETER = ImmutableSet.of(
":formstart",
"_charset_",
":redirect",
":cq_csrf_token"
);

@Override
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
Resource formContainerResource = request.getResource();
String accessToken = apiTokenService.getAccessToken();
ValueMap valueMap = formContainerResource.adaptTo(ValueMap.class);
if (valueMap != null) {
String endPointUrl = valueMap.get(REST_FORM_ENDPOINT_URL, String.class);
String[] recipients = valueMap.get("mailto", String[].class);
String redirect = valueMap.get(REDIRECT_PROP, String.class);
redirect = formContainerResource.getResourceResolver().map(redirect) + ".html";
if (StringUtils.isNotEmpty(endPointUrl)) {
HttpEntity formData;
CloseableHttpClient httpClient = HttpClients.createDefault();
int status = 200;
try {
formData = getFormData(request, recipients);
HttpPost httpPost = new HttpPost(endPointUrl);
httpPost.setHeader(AUTHORIZATION, BEARER + " " + accessToken);
httpPost.setEntity(formData);
HttpResponse httpResponse = httpClient.execute(httpPost);
LOGGER.info("response {}", httpResponse.getStatusLine().getStatusCode() ) ;
LOGGER.info("response-body {}", EntityUtils.toString(httpResponse.getEntity(), "UTF-8"));
httpClient.close();
status = httpResponse.getStatusLine().getStatusCode();
assert httpResponse.getStatusLine().getStatusCode() == 200 : "API Error";
response.sendRedirect(redirect);
} catch (AssertionError e) {
LOGGER.error("Error", e);
response.setStatus(status);
} catch (IOException e) {
LOGGER.error("Error", e);
response.setStatus(status);
} finally {
httpClient.close();
}
}
}
}

public static HttpEntity getFormData(SlingHttpServletRequest request, String[] recipients) {
Map<String, RequestParameter[]> params = request.getRequestParameterMap();
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("Recipients", String.format("[%s]", Arrays.stream(recipients)
.map(s -> String.format("{\"Address\":\"%s\", \"Display\":\"%s\", \"RecipientType\":0}", s, s))
.collect(Collectors.joining(","))));
builder.addTextBody("Subject", "Test");
for (Map.Entry<String, RequestParameter[]> entry : params.entrySet()) {
if (!INTERNAL_PARAMETER.contains(entry.getKey())) {
RequestParameter[] v = entry.getValue();
RequestParameter p = v[0];
if (p == null) continue;
if (p.isFormField()) {
builder.addTextBody(entry.getKey(), p.getString());
} else {
try {
InputStream stream = p.getInputStream();
builder.addBinaryBody(entry.getKey(), stream, ContentType.parse(p.getContentType()), p.getFileName());
} catch (IOException e) {
LOGGER.error("Error", e);
}
}
}
}
return builder.build();
}

}

 

Hope this helps.

Avatar

Correct answer by
Employee Advisor

when your form is submitting to a servlet, write the following code in your servlet

Enumeration<String> params = request.getParameterNames();
while(params.hasMoreElements())
{
String paramName = params.nextElement();
System.out.println("The param Name is "+paramName);
String data = request.getParameter(paramName);System.out.println("The data  is "+data);
}

. You will get to see the parameters passed to your servlet. You can then process the data as needed