How to make a GET request in AEM using Apache Fluent
In this post, I am making a service of GET request and using that service in a servlet to show the data.
API URL = https://thesimpsonsquoteapi.glitch.me/quotes
We will hit this URL to get our data inside a service and using Apache Fluent and converting into formatted JSON using Jackson.
Service
import com.fasterxml.jackson.databind.ObjectMapper;
import org.osgi.service.component.annotations.Component;
import org.apache.http.client.fluent.Request;
import java.io.IOException;
@Component(service = ApiService.class, immediate = true)
public class ApiService {
private static final String apiUrl = “https://thesimpsonsquoteapi.glitch.me/quotes”;
public String getJson() throws IOException {
private String content;
content = Request.Get(apiUrl).execute().returnContent().toString();
ObjectMapper mapper = new ObjectMapper();
Object json = mapper.readValue(content, Object.class);
String indentedContent = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);
return indentedContent;
}
}
Servlet
import com.infield.aem.challenge.core.services.ApiService;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import javax.servlet.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
@Component(service = Servlet.class, property = {“service.description=Api Servlet”,
“sling.servlet.paths=/bin/api.json”,
“sling.servlet.extensions=json”
})
public class ApiServlet extends SlingSafeMethodsServlet {
// calling the service using @Reference annotation.
@Reference
private ApiService apiService;
@Override
protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse response) throws IOException {
PrintWriter out = response.getWriter();
out.println(apiService.getJson());
}
}
After that build your project on your local AEM instance and hit URL—
http://localhost:4502/bin/api.json
Then the output will be shown like this
Note –> Data in JSON can be random.
@Reference
https://hc.apache.org/httpcomponents-client-ga/tutorial/html/fluent.html
Recent Comments