Consuming RESTful Data in Java with Authentication

package com.eric.test;
 
import java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import org.apache.commons.codec.binary.Base64;
import com.google.gson.*;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.MalformedURLException;
 
/**
 * Class with a single, public, static method to provide a  REST consumer
 * which returns data as a JsonObject, with authentication.
 * 
 * @author Eric McCormick, @edm00se
 * src: http://edm00se.github.io/DevBlog/xpages/server-rest-with-authentication
 * 
 */
public class  MyDataConsumer {
 
	/**
	 * Modified copy of com.eric.restful CustRestConsumer GetMyData
	 * method. This one requires provides basic authentication with Base64
	 * encoding.
	 * 
	 * @param myUrlStr URL of the REST endpoint
	 * @return JsonObject of the REST data
	 */
	public JsonObject GetMyAuthenticatedRestData( String myUrlStr ) {
		JsonObject myRestData = new JsonObject();
		try{
			URL myUrl = new URL(myUrlStr);
			URLConnection urlCon = myUrl.openConnection();
			urlCon.setRequestProperty("Method", "GET");
			urlCon.setRequestProperty("Accept", "application/json");
			urlCon.setConnectTimeout(5000);
			//set the basic auth of the hashed value of the user to connect
			urlCon.addRequestProperty("Authorization", GetMyCredentials() );
			InputStream is = urlCon.getInputStream();
			InputStreamReader isR = new InputStreamReader(is);
			BufferedReader reader = new BufferedReader(isR);
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while( (line = reader.readLine()) != null ){
				buffer.append(line);
			}
			reader.close();
			JsonParser parser = new JsonParser();
			myRestData = (JsonObject) parser.parse(buffer.toString());
			
			return myRestData;
			
		}catch( MalformedURLException e ){
			e.printStackTrace();
			myRestData.addProperty("error", e.toString());
			return myRestData;
		}catch( IOException e ){
			e.printStackTrace();
			myRestData.addProperty("error", e.toString());
			return myRestData;
		}
	}
	
	/**
	 * Uses the Apache Commons codec binary Base64 package for encoding 
	 * of credentials, so none transmit 'in the open'.
	 * 
	 * @return String of credentials for use with authenticated REST source
	 */
	private String GetMyCredentials () {
		String rawUser = "SomeUsername";
		String rawPass = "SomePassword12345";
		String rawCred = rawUser+":"+rawPass;
		String myCred = Base64.encodeBase64String(rawCred.getBytes());
		return "Basic "+myCred;
	}
	
}





This is an example class for consuming data from a RESTful API with authentication, via java.net.URLConnection. The main (public) method returns a com.google.gson.JsonObject. The private method performs the credential assignment into Base64 encoded String, for addition to the request authorization header property.

This class depends the com.google.gson library, which could be swapped out for the com.ibm.commons.util.io.json with minimal effort; and also depends the org.apache.commons.codec.binary library for Base64 encoding.

For further break down, see my blog post on this class: http://edm00se.github.io/DevBlog/xpages/server-rest-with-authentication

Alternate version of this class, using the com.ibm.commons.util.io.json library: https://gist.github.com/edm00se/e5626f63ef7573fd2f3e

Java
Eric McCormick
October 22, 2014 11:07 AM
Rating
299

All code submitted to OpenNTF XSnippets, whether submitted as a "Snippet" or in the body of a Comment, is provided under the Apache License Version 2.0. See Terms of Use for full details.



No comments yetLogin first to comment...