我正在尝试使用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;
}
答案 0 :(得分: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
的代码是一个字符串,用于确定命令何时完成作业以停止从流中读取。我不知道你的程序的输出是什么,你可以参考我的代码修改适合你的。