Installing unirest-java with the Maven Assembly Plugin

Apache Maven Project

Managing dependencies for your Java applications is difficult, unless you have Maven!  Maven is an Apache build manager for Java projects.  In this post, we will use a Maven plugin (Maven Assembly) to pull all the unirest-java dependencies in one bundle/jar file.

Let’s get started (the steps below assume you already have Java and Git installed):

Update: If you’re building for Android, please refer to this post.

1.  Download/Install Maven

To check if you already have Maven in your machine, run

"mvn -version"

in your Terminal.  OS X prior to Maverick already comes with Maven.  If you don’t have Maven yet, you can head over to this download page and install it.  (Also make sure to set $JAVA_HOME accordingly).  If everything’s good, the output should look something like below:

Terminal output

Terminal output

2.  Clone the unirest-java repository

Pick a folder where you want to clone the unirest-java repository, and run..

"git clone https://github.com/Mashape/unirest-java.git

This will download the source for unirest-java.  Note that in the root folder, there’s a pom.xml file.  This contains the directive for the Maven Assembly Plugin to generate a jar file of the unirest-java library bundled together with the required 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:

/target folder

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):

Import jar file into project

Here’s a sample code that uses unirest-java:

import com.mashape.unirest.http.*;
import com.mashape.unirest.http.exceptions.UnirestException;
 
public class HelloMashape {
 
    public static void main(String[] args) throws UnirestException {
 
		HttpResponse<String> request = Unirest.get("https://yoda.p.mashape.com/yoda?sentence=You%20will%20learn%20how%20to%20speak%20like%20me%20someday.%20%20Oh%20wait.")
				.header("X-Mashape-Authorization", "<Insert your Mashape key here>")
				.asString();
 
		System.out.println(request.getCode());
 
	}
}