Public API – Android CREATE Custom Action with Custom Data

The following code demonstrates how to create a custom action with custom data 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_CUSTOM_ACTION = "https://api.bluedotinnovation.com/1/actions/";
 
/**
 * Starts task for creating a new Custom Action with Custom Data
 * @param customerApiKey
 * @param lastApiKey
 * @param zoneId
 */
private void executePostCustomAction(String customerApiKey, String lastApiKey, String zoneId) {
    String postData = generatePOSTCustomActionRequest(customerApiKey, lastApiKey, zoneId);
    new ExecutePostRequest().execute(new String[]{PUBLICAPI_URL_ACTION, 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);
 
        InputStream is;
 
        if (http_status==200) {
            //Get Response
            is = connection.getInputStream();
 
        } else {
            //Get Error Response
            is = connection.getErrorStream();
 
        }
 
        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 Custom Action with Custom Data

/**
 * The following code shows how to form the JSON request for POST Custom Action with Custom Data
 * @param customerApiKey
 * @param apiKey
 * @param zoneId
 * @return JSON String
 */
private String generatePOSTCustomActionRequest(String customerApiKey, String apiKey, String zoneId){
    String result = null;
    // form the JSON string for request
    try{
        JSONObject customActionObject = new JSONObject();
        customActionObject.put("name", "A Custom Action");
        JSONArray customFieldsJsonArray = new JSONArray();
        customActionObject.put("customFields",customFieldsJsonArray);
        String[] keys = {"type", "name", "id"};
        String[] values = {"Coffee Shop", "Blue Bottle Coffee", "48707775-4991-434b-ba3a-f41ac1236c44"};
        JSONObject customFieldJsonObject;
        for(int i = 0 ; i < keys.length ; i++) {
            customFieldJsonObject = new JSONObject();
            customFieldJsonObject.put("key", keys[i]);
            customFieldJsonObject.put("value", values[i]);
            customFieldsJsonArray.put(customFieldJsonObject);
        }
        JSONArray customActionArray = new JSONArray();
        customActionArray.put(customActionObject);
        JSONObject actionObject = new JSONObject();
        actionObject.put("customActions",customActionArray);
        JSONObject zoneObject = new JSONObject();
        zoneObject.put("zoneId",zoneId);
        zoneObject.put("actions", actionObject);
        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, "generatePOSTCustomActionRequest(): " + e );
    }
    return result;
}
Created by Bluedot DevOps on March 5, 2018

Start the discussion