Java.gif

Previous: Supported Languages

Contents


64-warn.gif
NOTE: GoGrid Support WILL NOT troubleshoot customer-modified code. The code snippets and examples provided in this API documentation can be modified to customize your own code, but GoGrid Support cannot troubleshoot any errors you may receive due to missing syntax or illegal arguments. We WILL support our API interface and can troubleshoot any API server-side errors you may be receiving. Please note that all of the code snippets and examples provided in this API documentation have been thoroughly tested and verified as properly working.


Prerequisites

  • JDK 1.5 or Higher

GoGridClient.java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

/**
 * @author Servepath
 * 
 * This class demonstrates how to generate and submit signed HTTP requests to
 * the GoGrid REST API
 * 
 */
public class GoGridClient
{
  // Default value for result format, can be xml, json or csv
  private String m_format  = "xml";

  // Default value for the api server URL
  private String m_server  = "https://api.gogrid.com/api";

  // Default api key value, this is where developers can put their api key
  private String m_apikey  = "YOUR API KEY";

  // Default secret value, this is where developers can put their secret
  private String m_secret  = "YOUR SHARED SECRET";

  // Default version value, should never really change until there are more
  private String m_version = "1.0";

  /**
   * Default Constructor using default configuration
   */
  public GoGridClient()
  {

  }

  /**
   * Full Constructor
   * 
   * @param server
   *          Base url for the gogrid api server
   * @param apikey
   *          API Key to use to sign requests
   * @param secret
   *          Shared secret used to sign requests
   * @param format
   *          Format of the response - xml, json or csv
   * @param version
   *          API Version
   */
  public GoGridClient(String server, String apikey, String secret,
      String format, String version)
  {
    if (server != null)
    {
      m_server = server;
    }
    if (apikey != null)
    {
      m_apikey = apikey;
    }
    if (secret != null)
    {
      m_secret = secret;
    }
    if (format != null)
    {
      m_format = format;
    }
    if (version != null)
    {
      m_version = version;
    }
  }

  /*
   * Build a signed request url for the API
   * 
   * Note : values for api_key and secret passed in through params will be
   * ignored.
   */
  public String getRequestURL(String method, HashMap<String, String> inputparams)
      throws Exception
  {
    // Start building the local parameter map
    HashMap<String, String> params = new HashMap<String, String>();
    // Put the default values for format ant version into the local
    // param map
    params.put("format", m_format);
    params.put("v", m_version);

    // Begin the request URL string with the server and method
    String requestURL = m_server + "/" + method + "?";

    // Copy the passed in parameters into the local map
    for (Map.Entry<String, String> entry : inputparams.entrySet())
    {
      String key = entry.getKey();
      String value = entry.getValue();
      params.put(key, value);
    }

    // Put the apikey into the params here to make sure it is not
    // overwritten by a passed in param
    params.put("api_key", m_apikey);
    // Generate and put the signature value in the params
    params.put("sig", getSignature(m_apikey, m_secret));

    // Append all of the URL params to the request string,
    // URL encoding the values
    for (Map.Entry<String, String> entry : params.entrySet())
    {
      String key = entry.getKey();
      String value = URLEncoder.encode(entry.getValue(), "UTF-8");
      requestURL += "&" + key + "=" + value;
    }

    return requestURL;
  }

  /*
   * Get a URL signature value for a particular key and secret
   */
  public static String getSignature(String key, String secret) throws Exception
  {

    // Get the current epoch time
    long timestamp = (java.util.Calendar.getInstance().getTimeInMillis()) / 1000;

    // Construct the string to generate the signature print
    String s = key + secret + timestamp;

    // Create an MD5 hash of the string
    String sig = md5(s);

    return sig;
  }

  /*
   * Make the api request over HTTP
   */
  public String sendAPIRequest(String url) throws Exception
  {
    String response = "";

    URL myurl = new URL(url);
    HttpURLConnection con;
    if (myurl.getProtocol().equals("https"))
    {
      con = (HttpsURLConnection) myurl.openConnection();
    }
    else
    {
      con = (HttpURLConnection) myurl.openConnection();
    }
    // Try to read the response from the URL. If there are errors, java
    // will throw an exception. We catch them and return the code and body
    // of the error response.
    try
    {
      InputStream ins = con.getInputStream();
      InputStreamReader isr = new InputStreamReader(ins);
      BufferedReader in = new BufferedReader(isr);

      String inputLine;

      while ((inputLine = in.readLine()) != null)
        response += inputLine + "\n";

      in.close();
    }
    catch (Exception e)
    {
      // If reading the normal response body fails we end up here,
      // where we read the error stream and return that and the exception
      // message as the response, which can be used for debugging
      response = "Exception = " + e.getClass().getName() + "\n\nMessage = "
          + e.getMessage() + "\n\n";
      if (con.getErrorStream() != null)
      {
        BufferedReader reader = new BufferedReader(new InputStreamReader(con
            .getErrorStream()));

        String errorLine;
        while ((errorLine = reader.readLine()) != null)
        {
          response += errorLine + "\n";
        }
      }
    }

    return response;
  }

  // This is used by md5 hash
  public static String hex(byte[] array)
  {
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < array.length; ++i)
    {
      sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
    }
    return sb.toString();
  }

  /**
   * Generates a PHP compatible md5 hash
   */
  public static String md5(String message)
  {
    try
    {
      MessageDigest md = MessageDigest.getInstance("MD5");
      return hex(md.digest(message.getBytes("CP1252")));
    }
    catch (NoSuchAlgorithmException e)
    {
    }
    catch (UnsupportedEncodingException e)
    {
    }
    return null;
  }

} // GoGridClient class

GoGridExample.java

import java.util.HashMap;

public class GoGridExample
{

  /**
   * @param args
   */
  public static void main(String[] args)
  {
    GoGridClient client = new GoGridClient();
    try
    {
      HashMap<String, String> params = new HashMap<String, String>();
      params.put("format", "xml");

      String apiListUrl = client.getRequestURL("grid/server/list", params);
      String response = client.sendAPIRequest(apiListUrl);

      System.out.println(response);
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
  }
}

Previous: Supported Languages

Personal tools