Execute curl from java with processbuilder

11,918

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

Share:
11,918

Related videos on Youtube

michel.iamit
Author by

michel.iamit

As a big believer in an open society, helping each other with data and knowledge, I am a big fan of stackoverflow. Unfortunately time lacks to be very active here, but my goal is not only to get my own answers here, but help other finding theirs. Interests: ICT (no need to say here), open api's, system architecture, innovative and smart solutions, control engineering.

Updated on June 04, 2022

Comments

  • michel.iamit
    michel.iamit almost 2 years

    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/

  • michel.iamit
    michel.iamit almost 12 years
    ahhhh stupid me, of course! thanx! I just tested it, and indeed.... (I already knew before testing you were right)