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中编写测试程序来测试我与django中的restfull api的连接(精确地说是djangorestframework)。其中一个选择是用卷曲测试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和helptext。
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 /
1 个解决方案
#1
4
Each string you pass to the ProcessBuilder
constructor 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 "user
and a password of pwd"
.
如果您使用引号,那么它们将成为传递给流程的值的一部分,因此您尝试使用“user和密码为pwd”的用户名进行身份验证。
#1
4
Each string you pass to the ProcessBuilder
constructor 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 "user
and a password of pwd"
.
如果您使用引号,那么它们将成为传递给流程的值的一部分,因此您尝试使用“user和密码为pwd”的用户名进行身份验证。