Expand my Community achievements bar.

SOLVED

CloseableHttpClient can't execute in AEM

Avatar

Level 2

Hi 

I created a AEM servlet to call a external API and I tried to test it on local, my problem is that the CloseableHttpClient can not be executed.

@SlingServlet(paths={"/bin/test01"},methods= {"POST"},metatype=false)
public class OauthAuthServlet extends SlingAllMethodsServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = -4325654356300019990L;
	
    private  final Logger log = LoggerFactory.getLogger(OauthAuthServlet.class);
    
    CloseableHttpClient httpPostClient = HttpClients.createDefault();
	
	public static String OAUTH_SERVER_URL = "https://dm-us.informaticacloud.com/authz-service/oauth/token";

	@Override
    protected void doGet( SlingHttpServletRequest request,  SlingHttpServletResponse response) {
    	
		this.doPost(request, response);  	
    }
	
	@Override
    protected void doPost( SlingHttpServletRequest request,  SlingHttpServletResponse response){
    	String cc= request.getParameter("CLIENT_CREDENTIALS");
    	String token = null;
    	setLocalHttpProxy();
    	CloseableHttpClient httpClient = HttpClients.createDefault();
    	HttpPost httpPost = new HttpPost(OAUTH_SERVER_URL);
    	String header = "Basic "+cc;
    	httpPost.addHeader("Authorization", header);
    	List<NameValuePair> formparams = new ArrayList<>();
    	formparams.add(new BasicNameValuePair("grant_type","client_credentials"));
    	try {
			httpPost.setEntity(new UrlEncodedFormEntity(formparams));
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
			httpPost.setConfig(requestConfig);
			CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
			try {
				HttpEntity entity = httpResponse.getEntity();
				token=EntityUtils.toString(entity);
			}catch(Exception e) {
				e.printStackTrace();
			}finally {
				httpResponse.close();
			}
    	}catch(Exception e) {
    		e.printStackTrace();
    	}finally {
    		try {
    			httpClient.close();
    		}catch(Exception e) {
    			e.printStackTrace();
    		}
    	}

    	try {
			response.getWriter().write(token);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

The servlet always skip this line "

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);", I don't see any errors pop up in logs.

Please give me some advises, thank you.

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Hi @HanL1 

 

I made few changes on your code and executed it on my local. Servlet is getting executed and response is coming back. Let me know if are still facing any issue.

 

@Component(
service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Custom Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths=" + "/bin/test"
}
)
public class OauthAuthServlet extends SlingAllMethodsServlet {
/**
*
*/
private static final long serialVersionUID = -4325654356300019990L;

private final Logger log = LoggerFactory.getLogger(OauthAuthServlet.class);

CloseableHttpClient httpPostClient = HttpClients.createDefault();

public static String OAUTH_SERVER_URL = "https://dm-us.informaticacloud.com/authz-service/oauth/token";

@Override
protected void doGet( SlingHttpServletRequest request, SlingHttpServletResponse response) {

this.doPost(request, response);
}
@Override
protected void doPost( SlingHttpServletRequest request, SlingHttpServletResponse response) {
CloseableHttpClient httpClient = null;
try {
String cc= request.getParameter("CLIENT_CREDENTIALS");
String token = null;
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(OAUTH_SERVER_URL);
String header = "Basic "+cc;
httpPost.addHeader("Authorization", header);
List<NameValuePair> formparams = new ArrayList<>();
formparams.add(new BasicNameValuePair("grant_type","client_credentials"));
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
token=EntityUtils.toString(entity);
response.getWriter().write(token);
httpClient.close();
}catch (IOException e) {
throw new RuntimeException(e);
} catch(Exception e) {
e.printStackTrace();
}
}}

 

View solution in original post

4 Replies

Avatar

Community Advisor

Hi @HanL1 

 

Your servlet looks good to me however, we can try few options:-

 

1. Comment out this line 

	RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
			httpPost.setConfig(requestConfig);

2. Instead of using 

CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

 

try with, 

org.apache.http.HttpResponse

 

Also, you have used lots of nested try and catch block, add only one try and catch block. Make these changes and give it a try. 

Avatar

Correct answer by
Community Advisor

Hi @HanL1 

 

I made few changes on your code and executed it on my local. Servlet is getting executed and response is coming back. Let me know if are still facing any issue.

 

@Component(
service=Servlet.class,
property={
Constants.SERVICE_DESCRIPTION + "=Custom Servlet",
"sling.servlet.methods=" + HttpConstants.METHOD_POST,
"sling.servlet.paths=" + "/bin/test"
}
)
public class OauthAuthServlet extends SlingAllMethodsServlet {
/**
*
*/
private static final long serialVersionUID = -4325654356300019990L;

private final Logger log = LoggerFactory.getLogger(OauthAuthServlet.class);

CloseableHttpClient httpPostClient = HttpClients.createDefault();

public static String OAUTH_SERVER_URL = "https://dm-us.informaticacloud.com/authz-service/oauth/token";

@Override
protected void doGet( SlingHttpServletRequest request, SlingHttpServletResponse response) {

this.doPost(request, response);
}
@Override
protected void doPost( SlingHttpServletRequest request, SlingHttpServletResponse response) {
CloseableHttpClient httpClient = null;
try {
String cc= request.getParameter("CLIENT_CREDENTIALS");
String token = null;
httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(OAUTH_SERVER_URL);
String header = "Basic "+cc;
httpPost.addHeader("Authorization", header);
List<NameValuePair> formparams = new ArrayList<>();
formparams.add(new BasicNameValuePair("grant_type","client_credentials"));
httpPost.setEntity(new UrlEncodedFormEntity(formparams));
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
httpPost.setConfig(requestConfig);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
token=EntityUtils.toString(entity);
response.getWriter().write(token);
httpClient.close();
}catch (IOException e) {
throw new RuntimeException(e);
} catch(Exception e) {
e.printStackTrace();
}
}}

 

Avatar

Level 2

Hi @Avinash_Gupta_ 

Thank you for your response , I tried it but still doesn't work. It turns out it's proxy issue since I am using company laptop.