从Java执行Curl

时间:2017-12-04 17:39:41

标签: java curl

我正在尝试从Java执行以下curl命令,但我得到的答案是错误的,因为它总是返回状态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/

我正确地发送了用户" admin2"用他的密码进行身份验证。我认为问题是在我的代码中使用了字符(")。

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 个答案:

答案 0 :(得分:0)

在“命令”中,尝试从

中删除单引号
"'admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI'"

这样就变成了

"admin2:0xdRv63RKq2MtA326BNGQAI6yA1QNGO09enamGxI"

看看是否有帮助。它可能会将它们视为实际用户名和密码的一部分。

我认为在这种情况下问题是Json,我认为你是正确的双引号是问题。尝试将Json放在一个文件中,并使用curl将文件内容作为邮件正文发送。

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/"};