从Android App运行Google Apps脚本? [英] Run a Google Apps Script from Android App?

查看:86
本文介绍了从Android App运行Google Apps脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在我创建的Google Apps脚本网络应用上运行GET调用.我想在我的Android应用程序(IntentService)中按一个按钮后执行此GET调用.

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).

但是,我不确定如何执行授权流程,因为Google Apps脚本旨在在用户自己的Gmail帐户上运行(它会以用户正在访问网络应用程序"的身份执行清理脚本).

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" ).

我是否可以通过身份验证来从我的Android应用程序触发用户相关的Google Apps脚本?

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

推荐答案

确定.以下代码对我有用.

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();

调用 connection.getResponseCode()对于使实际请求继续进行很重要. sessionManager.getCreadentials()是我的Singleton Application类,它返回 GoogleAccountCredential 对象,这是oAuth2身份验证过程所必需的.

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.

最后,此代码将在Google脚本中的doPost函数中输入:

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);
   }
}

这篇关于从Android App运行Google Apps脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆