如何在Groovy中高效简洁地发送GET请求至REST API并将响应数据存入变量
Simplest Groovy Implementation for Fetching REST API Data
Here's the most concise and efficient way to hit your REST API, fetch the numeric list response, and store it as a Groovy list object—using only Groovy's built-in utilities (no external dependencies required):
import groovy.json.JsonSlurper // Replace with your actual API endpoint def apiEndpoint = "https://your-api-url.com/your-endpoint" // Fetch response and parse directly into a list def responseData = new JsonSlurper().parseText(new URL(apiEndpoint).text) // Verify the result (optional) println "Response type: ${responseData.getClass().simpleName}" // Outputs ArrayList println "First value: ${responseData[0]}" // Outputs 200
Why this works:
new URL(apiEndpoint).textmakes a GET request and returns the raw JSON response string in one line—Groovy handles the underlying HTTP connection boilerplate for you.JsonSlurperis Groovy's built-in JSON parser that automatically converts the JSON array into a native GroovyList<Integer>—exactly the object type you need.
Optional: Adding error handling
If you want to handle cases like network timeouts, invalid endpoints, or malformed JSON, wrap the code in a try-catch block:
import groovy.json.JsonSlurper def apiEndpoint = "https://your-api-url.com/your-endpoint" def responseData = [] try { def jsonResponse = new URL(apiEndpoint).text responseData = new JsonSlurper().parseText(jsonResponse) } catch (IOException e) { println "Failed to connect to API: ${e.message}" } catch (Exception e) { println "Failed to parse response: ${e.message}" } // Use responseData safely if (!responseData.isEmpty()) { println "Fetched ${responseData.size()} values" }
Optional: Custom headers (e.g., authentication)
If your API requires headers like an auth token, use URLConnection for more control:
import groovy.json.JsonSlurper def apiEndpoint = "https://your-api-url.com/your-endpoint" def connection = new URL(apiEndpoint).openConnection() connection.setRequestProperty("Authorization", "Bearer your-token") connection.setRequestProperty("Accept", "application/json") def responseData = new JsonSlurper().parse(connection.getInputStream())
内容的提问来源于Stack Exchange,提问作者匿名用户
相关产品推荐
相关产品推荐

