使用 processbuilder 从 java 执行 curl

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11442344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 05:09:11  来源:igfitidea点击:

Execute curl from java with processbuilder

javajsoncurlprocessbuilderdjango-rest-framework

提问by michel.iamit

I Am writing a test porgram in java to test my connections to a restfull api in django (djangorestframework to be precisely). One of the options is to test on of the api's with curl. Running the curl command from the shell it works fine: e.g.:

我正在用java编写一个测试porgram来测试我与django中restfull api的连接(准确地说是djangorestframework)。选项之一是使用 curl 测试 api。从 shell 运行 curl 命令它工作正常:例如:

curl --show-error --request GET --header 'Accept: application/json' --user "user:pwd" http://127.0.0.1:8000/api/v1/

this returns nicely the api root urls and helptext in json format.

这会很好地返回 json 格式的 api 根 url 和帮助文本。

Now when I try to invoke the same from java, using ProcessBuilder, i get this answer:

现在,当我尝试使用 ProcessBuilder 从 java 调用相同的代码时,我得到了这个答案:

{"detail": "You do not have permission to access this resource. You may need to login or otherwise authenticate the request."}

the java code I Am using is:

我正在使用的java代码是:

ProcessBuilder p=new ProcessBuilder("curl","--show-error", "--request","GET",
                    "--header","'Accept: application/json'", "--user","\"" + userName + ":" + password + "\"", getApiRootUrlString());
final Process shell = p.start();

Because I also catch the error stream by:

因为我还通过以下方式捕获错误流:

InputStream errorStream= shell.getErrorStream();
InputStream shellIn = shell.getInputStream();

I Know he starts the curl command, because making a mistake in one of the options shows the curl help text.

我知道他启动 curl 命令,因为在其中一个选项中出错会显示 curl 帮助文本。

I Am not quit sure what's the difference between invoking it, pretty sure it's the same command.

我不确定调用它有什么区别,很确定它是相同的命令。

by the way, 'getApiRootUrlString()' returns the correct url: http://127.0.0.1:8000/api/v1/

顺便说一句,'getApiRootUrlString()' 返回正确的 url: http://127.0.0.1:8000/api/v1/

回答by Ian Roberts

Each string you pass to the ProcessBuilderconstructor represents one argument, so you don't need the quotes that you would have to use with the shell. Try the following:

您传递给ProcessBuilder构造函数的每个字符串都代表一个参数,因此您不需要在 shell 中必须使用的引号。请尝试以下操作:

ProcessBuilder p=new ProcessBuilder("curl","--show-error", "--request","GET",
                "--header","Accept: application/json", "--user", userName + ":" + password, getApiRootUrlString());

If you use quotes then they become part of the value that's passed to the process, so you were trying to authenticate with a username of "userand a password of pwd".

如果您使用引号,那么它们将成为传递给进程的值的一部分,因此您尝试使用用户名"user和密码进行身份验证pwd"