Public API – Android CREATE Fence

The following code demonstrates how to create a fence using the Public API in an Android app using asynchronous URL call; HttpURLConnection is utilized for this particular example.

private final static String PUBLICAPI_URL_FENCE = "https://api.bluedotinnovation.com/1/fences";
 
/**
 * Starts task for creating a new Fence
 * @param customerApiKey
 * @param apiKey
 * @param zoneId
 */
private void executePostFence(String customerApiKey, String apiKey,String zoneId) {
    String postData = generatePOSTFenceRequest(customerApiKey, apiKey, zoneId);
    new ExecutePostRequest().execute(new String[]{PUBLICAPI_URL_FENCE, postData} );
}
  
// AsyncTask to perform the POST communication
private class ExecutePostRequest extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... params) {
        return executePost(params[0], params[1]);
    }
  
    @Override
    protected void onPostExecute(String result) {
        // Handle result if needed
        handleResult(result);
    }
}
 
/**
 * Executes a POST request for given url and post data
 * @param targetURL
 * @param postData
 * @return result string
 */
public String executePost(String targetURL, String postData)
{
    URL url;
    HttpURLConnection connection = null;
    Log.d(DEBUG_TAG, "executePost(): targetURL=" + targetURL);
    Log.d(DEBUG_TAG, "executePost(): postData=" + postData);
    try {
        // Get binary data
        byte[] outputBytes = postData.getBytes();
        //Create connection
        url = new URL(targetURL);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Content-Length", "" + Integer.toString(outputBytes.length));
        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);
  
        //Send request
        OutputStream wr = connection.getOutputStream();
        wr.write(outputBytes);
        wr.flush();
        wr.close();
  
        int http_status = connection.getResponseCode();
        Log.d(DEBUG_TAG, "executePost(): http_status=" + http_status);
  
        //Get Response
        InputStream is = connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer();
        while((line = rd.readLine()) != null) {
            response.append(line);
            response.append('\r');
        }
        rd.close();
        return response.toString();
  
    } catch (Exception e) {
        String errorMessage =  e.toString();
        Log.d(DEBUG_TAG, "executePost(): " + errorMessage);
        return errorMessage;
  
    } finally {
  
        if(connection != null) {
            connection.disconnect();
        }
    }
}

The following example shows how to form the JSON request for POST Fence

/**
 * The following code shows how to form the JSON request for POST Fence
 * @param customerApiKey
 * @param apiKey
 * @param zoneId
 * @return JSON String
 */
private String generatePOSTFenceRequest(String customerApiKey, String apiKey, String zoneId){
    String result = null;
    // form the JSON string for request
    try{
        JSONObject centerObject = new JSONObject();
        centerObject.put("latitude", "-37.8159544565362");
        centerObject.put("longitude", "144.9723565578461");
        JSONObject circleObject = new JSONObject();
        circleObject.put("name", "Test Circular fence with 8M radius");
        circleObject.put("color", "#000fff");
        circleObject.put("radius", "8");
        circleObject.put("center",centerObject);
        JSONArray circlesArray = new JSONArray();
        circlesArray.put(circleObject);
        JSONObject fencesObject = new JSONObject();
        fencesObject.put("circles", circlesArray);
        JSONObject zoneObject = new JSONObject();
        zoneObject.put("zoneId",zoneId);
        zoneObject.put("fences", fencesObject);
        JSONObject contentObject = new JSONObject();
        contentObject.put("zone", zoneObject);
        JSONObject securityObject = new JSONObject();
        securityObject.put("apiKey", apiKey);
        securityObject.put("customerApiKey", customerApiKey);
        JSONObject resultObject = new JSONObject();
        resultObject.put("security", securityObject);
        resultObject.put("content", contentObject);
        result = resultObject.toString();
    } catch (JSONException e){
        Log.e(DEBUG_TAG, "generatePOSTFenceRequest(): " + e );
    }
    return result;
}
Created by Bluedot DevOps on March 5, 2018

Start the discussion