gpt4 book ai didi

java - 无法通过 java Runtime.getRuntime().exec() 执行 CURL 命令

转载 作者:搜寻专家 更新时间:2023-10-31 20:10:41 27 4
gpt4 key购买 nike

我正在使用 java 执行 curl 命令。

curl -i --user "OAMADMIN_tenant_358922247351079_svc_358922247369079_APPID:Iuj.2swilg5fhv" -H "Content-Type: application/json" -H "Accept: application/json" -H 'X-USER-IDENTITY-DOMAIN-NAME: tenant_358922247351079' -H "X-RESOURCE-IDENTITY-DOMAIN-NAME: tenant_358922247351079" --request GET "https://slc04yre-1.dev.oraclecorp.com:4443/oam/services/rest/11.1.2.0.0/oauth/admin/Clients?name=myMCS_svc_358922247369079_MCS_Client_OAUTHCLIENT"

我想在我的代码中获取此 curl 命令的输出,但我的标准输出结果为空。

 private static String executeCommand(String command) {
StringBuffer output = new StringBuffer();

Process p;
try {
p = Runtime.getRuntime().exec(command);

BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
//p.waitFor();
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println("line="+line);
output.append(line + "\n");
}

} catch (Exception e) {
e.printStackTrace();
}

return output.toString();

}

尝试手动执行 curl 命令,它工作正常。然后我打印了标准错误,我可以看到:

   [testng] error line=
[testng] error line=curl: (6) Couldn't resolve host 'application'
[testng] error line=
[testng] error line=curl: (6) Couldn't resolve host 'application'
[testng] error line=
[testng] error line=curl: (6) Couldn't resolve host 'tenant_359516638431079''
[testng] error line=
[testng] error line=curl: (6) Couldn't resolve host 'tenant_359516638431079"'
[testng] error line=
[testng] error line=curl: (1) Unsupported protocol: "https

当手动执行 curl 命令时,它工作正常,那么为什么不通过 Runtime.getRuntime() 呢?

求推荐!!任何帮助将不胜感激。

最佳答案

数据外壳/控制台似乎正在解释/更改字符。例如下面一行:

-H "Content-Type: application/json"

... 似乎被解释为三个不同的论点:

-H Content-Type:application/json 由 shell/console。

尝试使用以下格式将命令字符串分解为组件数组:

exec(String[] cmdarray)

这样,shell/控制台就会清楚哪些参数组合在一起。

这是证明这一点的 groovy 测试:

def Object executeCommand(command) {

def proc = Runtime.getRuntime().exec(command);
def sout = new StringBuffer()
def serr = new StringBuffer()

proc.consumeProcessOutput(sout, serr)
proc.waitFor()

return [ 'sout':sout.toString(), 'serr':serr.toString() ]
}

response = executeCommand('''curl --silent --show-error -H "Accept: application/json" --request GET "https://education.cloudant.com/"''')
assert response['sout'] == ''
assert response['serr'].startsWith( 'curl: (6) Could not resolve host: application' )

response = executeCommand(['curl', '--silent', '--show-error', '-H', 'Accept: application/json', '--request', 'GET', 'https://education.cloudant.com/'] as String[] )
assert response['sout'].startsWith('{"couchdb":"Welcome","version":"1.0.2","cloudant_build":"2367"}')
assert response['serr'] == ''

关于java - 无法通过 java Runtime.getRuntime().exec() 执行 CURL 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30301212/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com