0

I am trying to execute the following curl command from Java, but the answer I get is incorrect, since it always returns the status 401.

curl -k -v -u "admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI" -d "{"username":"test","token_code":"246212"}" -H "Content-Type: application/json" https://192.168.101.59/api/v1/auth/

I am sending correctly the user "admin2" with his password for the authentication. I think the problem is the use of character (") in my code.

String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
                "-d", "{\"username\":\"test\",\"token_code\":\"246212\"}","-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};

ProcessBuilder builder = new ProcessBuilder(command);
builder.redirectErrorStream(true);

String curlResult = "";
String line = "";

try {
    Process process = builder.start();
    BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while (true) {
        line = r.readLine();
        if (line == null) {
            break;
        }
        curlResult = curlResult + line;
    }
} catch (Exception e) {
    e.printStackTrace();
}

1 Answer 1

3

In 'command', try removing the single quotes from

"'admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI'"

so that it becomes

"admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI"

and see if that helps. It might be considering them as part of the actual username and password.

I think the issue is the Json in this case and I think you are right then that the double quotes are the issue. Try putting the Json in a file and use curl to send the file contents as the body of your message.

String[] command = {"curl", "-k", "-v", "-u","admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI",
            "-d", "@/path/to/filename.json", "-H", "Content-Type: application/json", "https://192.168.101.59/api/v1/auth/"};
Sign up to request clarification or add additional context in comments.

5 Comments

I'm so sorry. I had tried with "admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI" but the response is the same
No, the service's response is the same (status 401).
@BrayanReyes Edited my response. If you can't live with the json in a file then you'll need to do further research on escaping a json payload in curl.
forgive me for the delay. I tried your code and solved my problem. Thanks so much! :)
@BrayanReyes Awesome, glad that worked for you! Also, if you'd kindly accept this answer I'd greatly appreciate it. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.