java 中的 curl 命令

2022-09-02 04:33:32

首先,我已经看过几个文档,关于同一个的堆栈溢出问题。我有我的项目特定问题当尝试运行命令时:

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

从Mac终端,我得到我想要的json格式数据。但是从java代码运行相同的命令,我在控制台中收到未经授权的401错误。我的代码是:

    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();
        }

我得到未经授权的401错误和一堆html标签。这似乎是一个重复的问题,但我已经尝试了所有的方法。我知道替代方案是使用http响应方法,但特别是我想使用curl命令。提前致谢。


答案 1

尝试更改此行

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

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

答案 2

嘿,试试这个,我有同样的问题。它在我的终端中工作,与您的终端具有相同的错误。

String[] command = {"curl", "-u" , username+ ":" + password , url};

推荐