Java Example

SAPI endpoints can easily be called from a standard Java or an Enterprise Java web application. The examples below are standard Java, but should still apply no matter what framework you may be using.

Prerequisites

In order for this example to work, you will need:

Tip: It is possible to access SAPI through an HTTP proxy, but it is not covered here. See the java.net.URL class documentation for more details.

Basic Example

The following example calls the Search endpoint and prints the name and primaryAddress.addressLine fields for each listing returned in the first page of results.

APIExample.java

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import java.io.InputStream;

import java.util.List;
import java.util.LinkedList;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

public class APIExample {

    private static final String API_KEY = "..."; // TODO: put your API key here

    private void search(String query, String location) throws Exception {
    
        // construct url for the search endpoint
        URL searchUrl = new URL("http://api.sensis.com.au/v1/test/search?key=" + API_KEY
                 + "&query="
                 + URLEncoder.encode(query, "UTF-8")
                 + "&location="
                 + URLEncoder.encode(location, "UTF-8"));
        
        // open connection to the server
        HttpURLConnection conn = (HttpURLConnection)searchUrl.openConnection();
        conn.connect();
        
        try {
        
            // ensure HTTP 200 (OK) response
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException(
                        "Error calling Search API (HTTP status "
                        + conn.getResponseCode() + ")");
            }
            
            // grab the response stream
            InputStream stream = conn.getInputStream();
            
            // parse JSON response
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readValue(stream, JsonNode.class);
      
            // grab the reponse code and message
            int code = root.get("code").getIntValue();
            String message = root.get("message").getTextValue();

            // ensure successful status code
            switch (code) {
                case 200: // success
                    break;
                default:
                    throw new RuntimeException(
                            "API returned error: " + message + ", code: " + code);
            } 
 
            System.out.println("Total results found: " + 
                    root.get("totalResults").getIntValue());

            // iterate over the results
            for (JsonNode result : root.get("results")) {
                // print the business name and display address
                System.out.println(result.path("name").getTextValue() 
                        + " (" + result.path("primaryAddress").path("addressLine").getTextValue() + ")");
            }     
            
            stream.close();                           
        
        } finally {
            conn.disconnect(); // ensure we always close the connection
        }
    
    }    

    public static void main(String[] args) throws Exception {
        new APIExample().search("hairdresser", "st kilda, vic");
     
    }
    
}

Calling Other Endpoints

Calling the other endpoints is also easy. The simplest way would be to adjust the value of the searchUrl variable in the first example. However, a slightly more elegant way would be to create a generic search function.

The following example contains a generic search function, that can be used to call any of the search endpoints, as well as return a given page of listings.

SSAPI.java

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import java.io.InputStream;

import java.util.List;
import java.util.LinkedList;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;

public class SSAPI { 

    public class Response {
    
        public int code;
        public String message;
        public int totalResults;
        public List<Listing> results = new LinkedList<Listing>();
    
    }
    
    public class Listing {
    
        public String name;
        public String addressLine;
    
    }
    
    private static final String API_KEY = "..."; // TODO: put your API key here

    private Response callEndpoint(String endpoint, String query, String location, Integer page, Integer rows) 
            throws Exception {
    
        // build path and query component of URL
        String path =  endpoint + "?key=" + API_KEY + "&query=" + URLEncoder.encode(query, "UTF-8");
    
        // add location parameter if given
        if (location != null) {
            path += "&location=" + URLEncoder.encode(location, "UTF-8");
        }
    
        // add page parameter if given
        if (page != null) {
            path += "&page=" + page;
        }
        
        // add rows parameter if given
        if (rows != null) {
            path += "&rows=" + rows;
        }
    
        // create URL from server and path
        URL searchUrl = new URL("http://api.sensis.com.au/v1/test/" + path);

        // open connection to the server
        HttpURLConnection conn = (HttpURLConnection)searchUrl.openConnection();
        conn.connect();
        
        try {
        
            // ensure HTTP 200 (OK) response
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new RuntimeException(
                        "Error calling Search API (HTTP status " 
                        + conn.getResponseCode() + ")");
            }
            
            // grab the response stream
            InputStream stream = conn.getInputStream();
            
            // parse JSON response
            ObjectMapper mapper = new ObjectMapper();
            JsonNode root = mapper.readValue(stream, JsonNode.class);
      
            Response response = new Response();
      
            // grab the reponse code and message fields
            response.code = root.get("code").getIntValue();
            response.message = root.get("message").getTextValue();

            // ensure status code is success or spell-checker run
            if (response.code != 200) {
                throw new RuntimeException(
                        "API returned error: " + response.message + 
                        ", code: " + response.code);
            }
            
            // grab the totalResults field
            response.totalResults = root.get("totalResults").getIntValue();

            // iterate over the results and add to list
            for (JsonNode result : root.get("results")) {
            
                Listing listing = new Listing();
                
                listing.name = result.path("name").getTextValue();
                listing.addressLine = result.path("primaryAddress").path("addressLine").getTextValue();
                
                response.results.add(listing);
            }     
            
            stream.close();      
            
            return response;                     
        
        } finally {
            conn.disconnect(); // ensure we always close the connection
        }
    
    }
    
    public Response search(String query, String location, Integer page, Integer rows)
            throws Exception {
    
        // call search endpoint with given parameters
        return callEndpoint("search", query, location, page, rows);
        
    }

    public Response getByListingId(int id) throws Exception {
        
        // call getByListingId endpoint
        return callEndpoint("getByListingId", String.valueOf(id), null, null, null);

    }
    
}

You could then create another class that calls the functions defined in SSAPI.java:

Example2.java

public class APIExample2 {

    private void printResults(SSAPI.Response response) {
        for (SSAPI.Listing listing : response.results) {
            System.out.println(
                    listing.name + " (" + listing.addressLine + ")");
        }
    }

    public void example() throws Exception {
    
        SSAPI ssapi = new SSAPI();
        SSAPI.Response response = ssapi.search("hairdresser", "st kilda, vic", null, null); // first page
        printResults(response);
        
        if (response.totalResults > response.results.size()) {
            response = ssapi.search("hairdresser", "st kilda, vic", 2, null); // second page
            printResults(response);
        }
    
    }
    
    public static void main(String[] args) throws Exception {
        new APIExample2().example();
    }

}