4
votes

I need to run a GET call on a Google Apps Script Web App I've created. I want to do this GET call after pressing a button in my Android App (IntentService).

However, I'm unsure how to do the authorization flow as the Google Apps Script is meant to run on the user's own Gmail Account (it executes a cleaning script as "the user accessing the web app" ).

Is there a way for me to authenticate such that I can trigger a user-dependent Google Apps Script from my Android App?

1

1 Answers

1
votes

OK. The following code works for me.

new AsyncTask<Void, Void, Void>() {

@Override
protected Void doInBackground(Void... params) {

    // The Google Script URL
    String googleAppsScriptURL = "https://script.google.com/macros/s/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX-o/dev";
    HttpURLConnection connection = null;
    try {
        URL url = new URL(googleAppsScriptURL + "?param1=foo&param2=bar");
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Bearer " + sessionManager.getCredentials().getToken());

        if(connection.getResponseCode() == 200) {
            // DO STUFF
        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (GoogleAuthException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  finally {
        if(connection != null) {
            connection.disconnect(); 
        }
    }
    return null;
}
}.execute();

Calling connection.getResponseCode() is important to get the actual request going. sessionManager.getCreadentials() is a Singleton Application class of mine that returns GoogleAccountCredential object, that is required for the oAuth2 Authentication process.

And finally this code will enter in doPost function in Google Scripts:

function doPost(e) {  
   if(typeof e !== 'undefined') {
    Logger.log(e.parameters.param1); // foo
    Logger.log( e.parameters.param2); // bar
    callYourFunction(e.parameter.param1, e.parameter.param2);
   }
}