Using OkHttp inside Liferay to consume external rest APIs. Problem with OSGi

Viewed 407

Inside a gradle java Liferay REST API backend (created with blade create -t rest), we are trying to use an OkHttp client from within Liferay 7.2 to access another rest API which is external.

The build.gradle dependencies include this line :

implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.9.0'

The build goes ok, but when we deploy the jar to the Liferay server, we got an error that says :

org.osgi.framework.BundleException: Could not resolve module: backendapp [1177]_  Unresolved requirement: Import-Package: okhttp3_ [Sanitized]
at org.eclipse.osgi.container.Module.start(Module.java:444)

Is OkHttp OSGI-ready for Liferay? and if not what is an LR-friendly alternative to consume rest APIs from inside a java inside LR?

Thanks for any hints.

3 Answers

Assuming OkHttp is delivered as a valid OSGi bundle: just building your plugin doesn't make its dependencies available to the runtime. You'll have to deploy it (and it's dependencies) to the runtime separately to make it available.

Of course this needs to happen just once, not every time you update your own plugin

you can add in below dependency in build.gradle

compileInclude group: "com.squareup.retrofit2", name: "retrofit", version: "2.5.0"
compileInclude group: "com.squareup.retrofit2", name: "converter-jackson", version: "2.5.0"
compileInclude group: 'org.cache2k', name: 'cache2k-all', version: '1.0.2.Final'
compileInclude group: 'com.squareup.okhttp3', name: 'okhttp', version: '4.2.2'

Also you need to add below lines in bnd.bnd file

Import-Package: \
!android.*,\
!com.android.*,\
!dalvik.system,\
!javax.annotation.meta,\
!kotlin.internal.jdk7,\
!kotlin.internal.jdk8,\
!kotlin.reflect.jvm.internal,\
!org.conscrypt,\
!org.openjsse.javax.net.ssl,\
!org.openjsse.net.ssl,\
!org.xmlpull.v1,\
!sun.security.ssl,\
*

Hope it works for you.

Related