• Register

Using the Mashery API with Java

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MasheryAPIExampleBase {
    protected static String masheryV2ApiKey = ""; //TODO: Enter your Mashery V2 API Key
    protected static String masheryV2ApiSecret = ""; //TODO: Enter your Mashery V2 API Secret
    protected static String siteIdFromDashboard = ""; //TODO: Enter your Mashery Site ID (from Dashboard)

    protected static int getResultTotalPages(String jsonResponse) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readValue(jsonResponse, JsonNode.class);
        JsonNode totalNode = rootNode.path("result").path("total_pages");
        return Integer.parseInt(totalNode.toString());
        
    }
    protected static String callMasheryAPI(String jsonString) throws Exception
    {
        long epoch = System.currentTimeMillis()/1000;
        String timestamp = Long.toString(epoch);
        String sig = MD5(masheryV2ApiKey + masheryV2ApiSecret + timestamp);  
        
        String urlStr = "http://api.mashery.com/v2/json-rpc";
        String urlParams ="apikey=" + masheryV2ApiKey + "&sig=" + sig;
        
        urlStr = urlStr + "/" + siteIdFromDashboard +"?" + urlParams;    

        URL url = new URL(urlStr);
        
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true); // Triggers POST.
        connection.setDoInput(true);
        connection.setReadTimeout(0);
        
        connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        connection.setRequestProperty("Content-Type", "application/json");
        OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());

        wr.write(jsonString);
        wr.flush();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer buf = new StringBuffer();
        while ((inputLine = in.readLine()) != null)
        {
            buf.append(inputLine);
        }
        
        wr.close();
        in.close();
        
        return buf.toString();
    }

    protected static String callMasheryReportingAPI(String reportingMethod, String reportingParams) throws Exception
    {
        long epoch = System.currentTimeMillis()/1000;
        String timestamp = Long.toString(epoch);
        String sig = MD5(masheryV2ApiKey + masheryV2ApiSecret + timestamp);  
        
        String urlStr = "http://api.mashery.com/v2/rest";
        
        String urlParams ="apikey=" + masheryV2ApiKey + "&sig=" + sig;
        
        urlStr = urlStr + "/" + siteIdFromDashboard + "/" + reportingMethod  +"?" + reportingParams + "&" + urlParams;    

        URL url = new URL(urlStr);
        
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        connection.setReadTimeout(0);
        
        connection.setRequestProperty("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
        connection.setRequestProperty("Content-Type", "application/json");

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuffer buf = new StringBuffer();
        while ((inputLine = in.readLine()) != null)
        {
            buf.append(inputLine);
            buf.append("\n");
        }
        
        in.close();
        
        return buf.toString();
    }
    private static String convertToHex(byte[] data) { 
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        return buf.toString();
    } 
 
    private static String MD5(String text) 
    throws NoSuchAlgorithmException, UnsupportedEncodingException  { 
        MessageDigest md;
        md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
    }
}

Docs Navigation