使用processbuilder从java执行curl
我正在java中编写测试程序来测试我与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/
这将以json格式很好地返回api根URL和helptext。
现在,当我尝试使用ProcessBuilder从java调用相同的内容时,我得到了这样的答案:
{"detail": "You do not have permission to access this resource. You may need to login or otherwise authenticate the request."}
我使用的java代码是:
ProcessBuilder p=new ProcessBuilder("curl","--show-error", "--request","GET", "--header","'Accept: application/json'", "--user","\"" + userName + ":" + password + "\"", getApiRootUrlString()); final Process shell = p.start();
因为我也通过以下方式捕获错误流:
InputStream errorStream= shell.getErrorStream(); InputStream shellIn = shell.getInputStream();
我知道他启动了curl命令,因为在其中一个选项中出错会显示curl帮助文本。
我不确定调用它之间的区别是什么,非常确定它是相同的命令。
顺便说一下,’getApiRootUrlString()’返回正确的URL: http://127.0.0.1:8000/api/v1/
: http://127.0.0.1:8000/api/v1/
:8000 / api / v1 /
传递给ProcessBuilder
构造函数的每个字符串都代表一个参数,因此您不需要使用shell必须使用的引号。 请尝试以下方法:
ProcessBuilder p=new ProcessBuilder("curl","--show-error", "--request","GET", "--header","Accept: application/json", "--user", userName + ":" + password, getApiRootUrlString());
如果您使用引号,那么它们将成为传递给流程的值的一部分,因此您尝试使用"user
和密码为pwd"
"user
名进行身份validation。