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

如何在Gradle.kts脚本中执行指定curl命令?执行报错求助

Gradle.kts中执行curl命令失败的解决方法

你的任务执行失败主要有三个原因:

  • Runtime.getRuntime().exec()不会等待curl命令执行完成就返回,导致Gradle任务结束时curl进程仍在运行,出现exitValue="Not exited"错误。
  • 直接将完整curl命令作为单个字符串传递,会被错误解析(尤其是包含+、冒号这类特殊字符和空格分隔的参数时),导致参数传递错误。
  • 未处理curl进程的输入输出流,缓冲区满时会造成进程阻塞。

推荐解决方案:使用Gradle内置Exec任务类型

Gradle提供了专门的Exec任务类型,能自动处理进程等待、参数解析和流处理,写法更可靠:

tasks.register("uploadProguardMapping") {
    doLast {
        exec {
            commandLine(
                "curl",
                "-v",
                "-H", "Content-Type:text/plain",
                "--upload-file", "mapping.txt",
                "--user", "Example+account:Example-License-Key-4e8ec2ae6cfe",
                "https://api.eum-appdynamics.com/v2/account/Example+account/com.example.networklogger/1/proguard-mapping"
            )
            // 将curl的输出和错误信息打印到Gradle控制台,方便调试
            standardOutput = System.out
            errorOutput = System.err
        }
    }
}

若坚持使用Runtime.exec的修正写法

如果必须用Runtime.exec,需要手动处理进程等待和流读取:

tasks.register("uploadProguardMapping") {
    doLast {
        val process = Runtime.getRuntime().exec(arrayOf(
            "curl",
            "-v",
            "-H", "Content-Type:text/plain",
            "--upload-file", "mapping.txt",
            "--user", "Example+account:Example-License-Key-4e8ec2ae6cfe",
            "https://api.eum-appdynamics.com/v2/account/Example+account/com.example.networklogger/1/proguard-mapping"
        ))
        // 读取输出流,避免进程阻塞
        process.inputStream.bufferedReader().use { println(it.readText()) }
        // 读取错误流
        process.errorStream.bufferedReader().use { println(it.readText()) }
        // 等待进程执行完成
        val exitCode = process.waitFor()
        if (exitCode != 0) {
            throw GradleException("curl命令执行失败,退出码:$exitCode")
        }
    }
}

额外注意事项

  • 确保mapping.txt文件位于任务执行的工作目录下,或者传入文件的绝对路径。
  • Windows环境需确认已安装curl(或替换为PowerShell的Invoke-WebRequest命令,写法需调整)。
  • 若为Android项目,可将该任务绑定到assembleRelease等生命周期任务之后,确保mapping文件已生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 16:03:17