-1

我正在尝试使用 java.net.URLConnection 发出 curl 请求。但是,当使用 --verbose 开关执行时,我需要解析命令的输出。

以下代码按预期执行 curl 请求,我只是在寻找一种方法来获取命令的详细输出。

        String stringUrl = this.contUrl + "/auth?action=login";
        URL url = new URL(stringUrl);
        URLConnection uc = url.openConnection();

        System.out.println(stringUrl);
        System.out.println("Authorization: " + this.header);

        uc.setRequestProperty("X-Requested-With", "Curl");
        uc.setRequestProperty("Authorization", this.header);

        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String result = "";
        String line;    
        while((line = in.readLine()) != null) {
            result += line;
        }
4

1 回答 1

0

我有一个从命令行读取输出的功能,希望对您有所帮助:

private String readCommandOutput(String pattern) throws IOException {
    BufferedInputStream bis = new BufferedInputStream(uc.getInputStream());
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    String charset = "utf-8";
    int result = bis.read();
    String output = "";
    String lineSeparator = System.getProperty("line.separator");
    while (result != -1) {
        buf.write((byte) result);
        output = buf.toString(charset);
        if (!output.equals(lineSeparator)) {
            String output_arr[] = output.split(lineSeparator);
            String lastLine = output_arr[output_arr.length - 1];

            // check if this is the end of stream and the pattern is match
            if (lastLine.endsWith(pattern) && bis.available() == 0) {
                return output;
            } 
        }           
        result = bis.read();
    }
    return buf.toString(charset);
}

我使用的这段代码pattern是一个字符串,用于确定命令何时完成它的工作以停止从流中读取。我不知道你程序的输出是什么,你可以参考我的代码来修改适合你的。

于 2017-07-11T23:08:40.400 回答