java中的curl命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31049555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
curl command in java
提问by lazy rabbit
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 :
首先,我已经看过几个文档,关于相同的 stackoverflow 问题..我有我的项目特定问题当尝试运行命令时:
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 :
从 mac 终端,我得到了我想要的 json 格式数据。但是从 java code 运行相同的命令,我在控制台中收到 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();
}
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.
我收到未经授权的 401 错误和一堆 html 标签。这似乎是一个重复的问题,但我已经尝试了所有方法。我知道替代方法是使用 http 响应方法,但特别是我想使用 curl 命令。提前致谢。
采纳答案by Andrzej Bobak
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};
回答by narmadha
hey try this I had the same problem. It worked in my terminal had the same error as yours.
嘿试试这个我有同样的问题。它在我的终端中工作,与您的错误相同。
String[] command = {"curl", "-u" , username+ ":" + password , url};