Execute curl from java with processbuilder

2019-05-05 19:58发布

问题:

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.:

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.

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

{"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:

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.

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/

回答1:

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 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".