You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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).text makes a GET request and returns the raw JSON response string in one line—Groovy handles the underlying HTTP connection boilerplate for you.
  • JsonSlurper is Groovy's built-in JSON parser that automatically converts the JSON array into a native Groovy List<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,提问作者匿名用户

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 19:28:10