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;
	}
	
}
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...