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

Groovy循环匹配条件中断、批量校验接口返回200的实现问题

原有代码问题分析

  1. 你使用的find方法逻辑是返回第一个匹配闭包条件的元素,当前闭包遇到200就返回true终止遍历,完全无法检测到200之后的非200状态码,和「所有接口都返回200才返回true」的需求完全相反
  2. mytest函数没有显式指定返回值,默认取find方法的执行结果,逻辑判断完全不符合预期

修正实现方案

1. 状态码模拟校验版本

使用Groovy集合内置的every方法,该方法只有所有元素都满足闭包条件时才返回true,遇到第一个不满足条件的元素就终止遍历,刚好匹配你的需求:

def mytest() {
    def statusList = [200, 200, 200, 300]
    // 可按需添加非200状态码的打印逻辑
    return statusList.every { status ->
        if (status != 200) {
            println "检测到非200状态码:${status}"
            return false
        }
        return true
    }
}

if (!mytest()) {
    println "Function returns false"
}

2. 实际curl接口校验版本

直接调用系统curl命令获取状态码,适配你的真实业务场景:

// 填入需要校验的接口地址
def apiList = [
    "https://example.com/api/1",
    "https://example.com/api/2",
    "https://example.com/api/3"
]

def checkAllApi() {
    return apiList.every { apiUrl ->
        // curl参数说明:-s静默模式,-o /dev/null丢弃响应体,-w输出状态码,--connect-timeout设置超时时间
        def curlCommand = ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--connect-timeout", "5", apiUrl]
        def process = curlCommand.execute()
        process.waitFor()
        def httpStatus = process.text.toInteger()
        if (httpStatus != 200) {
            println "接口${apiUrl}校验失败,状态码:${httpStatus}"
            return false
        }
        println "接口${apiUrl}校验正常"
        return true
    }
}

// 执行校验
def allSuccess = checkAllApi()
println "批量校验最终结果:${allSuccess}"

内容的提问来源于stack exchange,提问作者WhoAmI

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:18:05