Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
901 views
in Technique[技术] by (71.8m points)

curl command in java

First of all , i've already seen couple of documents, stackoverflow questions regarding the same ..I've my project specific question When trying to run command :

   curl -u username:password https://example.com/xyz/abc 

from the mac terminal , I get my desired json format data. But running the same command from java code , I get Unauthorised 401 error in console. My code is :

    String username="myusername";
    String password="mypassword";
    String url="https://www.example.com/xyz/abc";
       String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};
        ProcessBuilder process = new ProcessBuilder(command); 
        Process p;
        try
        {
            p = process.start();
             BufferedReader reader =  new BufferedReader(new InputStreamReader(p.getInputStream()));
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ( (line = reader.readLine()) != null) {
                        builder.append(line);
                        builder.append(System.getProperty("line.separator"));
                }
                String result = builder.toString();
                System.out.print(result);

        }
        catch (IOException e)
        {   System.out.print("error");
            e.printStackTrace();
        }

I get Unauthorised 401 error and bunch of html tags . It seems like a repetitive question, but I've tried all the approaches. I know alternative is using http response method, but particularly I want to use curl commands. Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try changing this line

String[] command = {"curl", "-u" ,"Accept:application/json", username, ":" , password , url};

into

String[] command = {"curl", "-H", "Accept:application/json", "-u", username+":"+password , url};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...