如何通过Java版Google API服务库获取Google Apps Script执行返回值
Got it, let's figure out how to fetch the return value from scripts.run using the Google Script Java client library. I'll walk you through the key steps and provide a complete working code example to clear this up.
First, make sure your project includes the Google Script client library and authentication dependencies. If you're using Maven, add these to your pom.xml:
<dependencies> <dependency> <groupId>com.google.apis</groupId> <artifactId>google-api-services-script</artifactId> <version>v1-rev20220727-2.0.0</version> </dependency> <dependency> <groupId>com.google.auth</groupId> <artifactId>google-auth-library-oauth2-http</artifactId> <version>1.14.0</version> </dependency> </dependencies>
Your getScriptService() method needs to handle authentication correctly. Here's a common implementation using a service account (adjust the credentials path to match your file):
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.json.gson.GsonFactory; import com.google.api.services.script.Script; import com.google.auth.http.HttpCredentialsAdapter; import com.google.auth.oauth2.GoogleCredentials; import java.io.FileInputStream; import java.io.IOException; import java.security.GeneralSecurityException; public Script getScriptService() throws IOException, GeneralSecurityException { // Load service account credentials GoogleCredentials credentials = GoogleCredentials.fromStream( new FileInputStream("path/to/your/service-account-key.json")) .createScoped("https://www.googleapis.com/auth/script.execution"); return new Script.Builder( GoogleNetHttpTransport.newTrustedTransport(), GsonFactory.getDefaultInstance(), new HttpCredentialsAdapter(credentials)) .setApplicationName("Your App Name") .build(); }
Now, let's put it all together to call your Apps Script function and get the return value. We'll use ExecutionRequest to define the function name and any parameters, then extract the result from the Operation response:
import com.google.api.services.script.model.ExecutionRequest; import com.google.api.services.script.model.Operation; import java.io.IOException; import java.security.GeneralSecurityException; import java.util.Collections; public class ScriptRunner { public static void main(String[] args) { try { String scriptId = "YOUR_SCRIPT_ID_HERE"; Script scriptService = getScriptService(); // 1. Create the execution request ExecutionRequest request = new ExecutionRequest() .setFunction("yourAppsScriptFunctionName") // Replace with your function name .setParameters(Collections.singletonList("optionalParameter")); // Add your params if needed // 2. Execute the script Operation response = scriptService.scripts().run(scriptId, request).execute(); // 3. Check for errors first if (response.getError() != null) { // Handle script execution errors System.err.println("Script execution error: " + response.getError().getMessage()); response.getError().getDetails().forEach(detail -> System.err.println("Detail: " + detail.getField() + " - " + detail.getMessage())); return; } // 4. Retrieve the return value Object returnValue = response.getResponse().get("result"); System.out.println("Script returned: " + returnValue); // If your return value is a complex object, cast it appropriately // Example: String resultString = (String) returnValue; // Example: List<String> resultList = (List<String>) returnValue; } catch (IOException | GeneralSecurityException e) { e.printStackTrace(); } } // Include the getScriptService() method from Step 2 here }
Key Notes:
- Replace
YOUR_SCRIPT_ID_HEREwith your actual Apps Script project ID. - Update
yourAppsScriptFunctionNameto match the function in your Apps Script project that you want to run. - If your function takes multiple parameters, replace
Collections.singletonList("optionalParameter")with a list containing all your parameters in the correct order. - Always check for
response.getError()first—this will catch issues like permission errors, invalid function names, or runtime errors in your Apps Script code. - The return value is an
Object, so you'll need to cast it to the appropriate type (String, List, Map, etc.) based on what your Apps Script function returns.
内容的提问来源于stack exchange,提问作者Heron Yang

