Using Unirest (Java) for your Android projects
← Back to Blog Home
This post will show you how to get Unirest-java running on your Android projects. Unirest is a lightweight HTTP client library with port available in many languages.
This is a follow-up to “How to install Unirest using the Maven assembly plugin”. The steps are similar, with the addition of a Maven (shader) plugin that relocates some packages in order to work around dependency errors when using the uber jar in an Android project. (In case you’re interested, the error you’ll get is ”java.lang.NoSuchFieldError: org.apache.http.message.BasicLineFormatter.INSTANCE”).
1. Follow Steps 1 and 2 from the Unirest-java/Maven tutorial. Once you’re done with those 2 steps, you should already have Maven working, and a clone of the Unirest-java repository.
2. Modify pom.xml in the cloned unirest-java repo to call the Maven shader plugin. You need to add the following inside the <plugins></plugins> tags.
This allows us to fix dependency references when using the Unirest uber JAR in Android. It calls the Maven shader plugin to relocate offending dependencies.
3. Call the Maven Assembly plugin
To invoke the assembly plugin, run…
"mvn clean assembly:assembly"
Run this in the root folder of your cloned unirest-java repository. This would pick up the directive in the pom.xml file and start bundling the unirest library into a jar file, along with its dependencies. It would also run unit tests to make sure everything’s good.
If successful, it should generate a /target folder with the following contents:
The jar file we need is underlined in the image above. We can then import this into our project like below (shown here in Eclipse):
Here’s a sample screenshot and code that uses unirest-java in an Android project (Download sample code from Github).
Hope this helps. If you have questions, tweet to @mashape