我正在 intellij 中构建一个插件并想发出 curl 请求。该插件是用 kotlin 编写的。
以下 curl 请求有效:
val comd = arrayOf(
"curl",
"-X",
"GET",
"-H",
"Authorization: AUTH_TOKEN",
"https://api.bitrise.io/v0.1/me"
)
但是以下带有数据的 POST 请求不会:
val comd = arrayOf(
"curl",
"-X",
"POST",
"https://api.bitrise.io/v0.1/apps/appslug/builds",
"-H",
"Authorization: AUTH_TOKEN",
" -d $data"
)
我正在使用这个函数来运行请求:
private fun executeCommandLine(project: Project, comd: Array<String>) {
val process = Runtime.getRuntime().exec(comd)
val processHandler: ProcessHandler = OSProcessHandler(process, "clear", Charset.forName("UTF-8"))
consoleView.attachToProcess(processHandler)
processHandler.startNotify()
}
它只是抛出一个错误:
curl: (3) nested brace in URL position 18:
-d {"hook_info":{"type":"bitrise"},"build_params":{"branch":"master"}}
我已经尝试使用 -g 开关运行请求以解决 globbing 错误。但后来我遇到了另一个:
curl: (3) URL using bad/illegal format or missing URL
我在这里错过了什么?
PS:我不得不将我的 curl 命令分解成一个数组,否则它不起作用。检查这个:Unable to execute CURL command through java Runtime.getRuntime().exec()
提前致谢:)
最佳答案
将 curl 命令返回到一个字符串,然后尝试使用 @leondepeon 的 answer 中的这个函数
/** Run a system-level command.
* Note: This is a system independent java exec (e.g. | doesn't work). For shell: prefix with "bash -c"
* Inputting the string in stdIn (if any), and returning stdout and stderr as a string. */
fun exec(cmd: String, stdIn: String = "", captureOutput:Boolean = false, workingDir: File = File(".")): String? {
try {
val process = ProcessBuilder(*cmd.split("\\s".toRegex()).toTypedArray())
.directory(workingDir)
.redirectOutput(if (captureOutput) ProcessBuilder.Redirect.PIPE else ProcessBuilder.Redirect.INHERIT)
.redirectError(if (captureOutput) ProcessBuilder.Redirect.PIPE else ProcessBuilder.Redirect.INHERIT)
.start().apply {
if (stdIn != "") {
outputStream.bufferedWriter().apply {
write(stdIn)
flush()
close()
}
}
waitFor(60, TimeUnit.SECONDS)
}
if (captureOutput) {
return process.inputStream.bufferedReader().readText()
}
} catch (e: IOException) {
e.printStackTrace()
}
return null
}
此外,如果在 Windows 上工作,be wary of the single quote .
关于使用带有数据的 Runtime.getRuntime.exec 错误的 kotlin 中的 CURL POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61030427/