HttpClient and Liferay 7 OSGi modules

 HttpClient and Liferay 7 OSGi modules


Overview


Apache HttpClient is a popular library, which simplifies interaction with remote HTTP server or API.

But, as with any third-party library, it’s tricky to make it work inside Liferay’s OSGi world. This article explains how to do it.


Configuration


build.gradle:

compileOnly group: "org.apache.httpcomponents", name: "httpclient", version: "4.5.11"

compileOnly group: "org.apache.httpcomponents", name: "httpcore", version: "4.4.13"


bnd.bnd:

Bundle-Name: LifeDev HttpClient Sample

Bundle-SymbolicName: com.lifedev.httpclient.sample

Bundle-Version: 1.0.0

Export-Package: com.lifedev.httpclient.sample.constants

-includeresource: \

  lib/httpclient.jar=httpclient-4.5.11.jar;lib:=true,\

  lib/httpcore.jar=httpcore-4.4.13.jar;lib:=true,\

   lib/commons-codec.jar=commons-codec-1.13.jar;lib:=true


Note: “-includeresource” part is important here. Otherwise, you may get errors like:

“Can not resolve module: [module] Unresolved requirement: ...”. Sample:


org.osgi.framework.BundleException: Could not resolve module: 

com.lifedev.httpclient.sample [1680]_  Unresolved requirement: 

Import-Package: org.apache.http_ [Sanitized]

at org.eclipse.osgi.container.Module.start(Module.java:444)



Sample Usage

Now, when you have deployed your OSGi module with httpclient, you can use it like this:


try (CloseableHttpClient client = HttpClients.createDefault()) {

   HttpPost httpPost = new HttpPost(getAccessTokenUrl);

   httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");

   List<NameValuePair> params = new ArrayList<NameValuePair>();

   params.add(new BasicNameValuePair("client_id", clientId));

   params.add(new BasicNameValuePair("client_secret", clientSecret));

   params.add(new BasicNameValuePair("grant_type", "client_credentials"));

   httpPost.setEntity(new UrlEncodedFormEntity(params));

   httpPost.setHeader("Accept", "application/json");

   CloseableHttpResponse response = client.execute(httpPost);

   int statusCode = response.getStatusLine().getStatusCode();

   if (statusCode == HttpStatus.SC_OK) {

       HttpEntity entity = response.getEntity();

       String getAccessTokenResponse = EntityUtils.toString(entity);

       JSONObject jsonObject = JSONFactoryUtil.createJSONObject(getAccessTokenResponse);

       accessToken = jsonObject.getString("access_token");

   } else {

       _log.warn("Invalid response code for getAccessTokenUrl: " + statusCode);

   }

}


This sample fetches the access_token for the OAuth2 Application in Liferay, to be used for Headless API authorization.


Enjoy 😏

Comments

Popular posts from this blog

Liferay Search Container Example

Liferay DXP - max upload file size

Liferay Keycloak integration