Java中的curl命令

首先,我已经看过几个文档,关于同一文档的stackoverflow问题。我在尝试运行命令时遇到了项目特定的问题:

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

从mac终端,我得到了所需的json格式数据。但是从Java代码运行相同的命令,控制台中出现Unauthorized 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命令。提前致谢。

回答:

尝试更改此行

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

进入

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

以上是 Java中的curl命令 的全部内容, 来源链接: utcz.com/qa/417081.html

回到顶部