4

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?

Rohan
  • 515
  • 10
  • 30

1 Answers1

1

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);
   }
}
kirilv
  • 1,373
  • 1
  • 18
  • 24
  • I know this is old, and I'm not expecting (or feeling entitled to) any response, but could something like this be used to create a trigger on a standalone script elsewhere from another script? I've asked the question here: https://stackoverflow.com/questions/67763540/user-installable-every-minute-trigger-to-standalone-script-via-button – Eliot Cole May 31 '21 at 14:46