Java ProcessBuilder 执行 curl 命令获取 ElasticSearch 数据。
部分 curl 命令参数说明
参数 | 说明 |
---|---|
-XGET | 指定 GET 命令 |
–tlsv1.2 | 指定通信协议为TLSv1.2 |
–negotiate | 使用HTTP身份验证 |
-k | 允许不使用证书到SSL站点 |
-u | 设置服务器的用户和密码 |
-H | 自定义头信息传递给服务器 |
-d | HTTP POST方式传送数据 |
static String[] curlArray = {"curl", "-XGET", "--tlsv1.2", "--negotiate", "-k", "-u", "username:password", "https://ip/index_name/_search?pretty=true", "-H", "Content-Type:application/json", "-d", "JSONString"};
public static void main(String[] args) throws Exception {
Process process = null;
try {
// 执行 url 命令
process = new ProcessBuilder(curlArray).start();
// 输出子进程信息
printStreamString(process);
// 等待子进程结束
process.waitFor();
} catch (InterruptedException e) {
// 强制关闭子进程(如果打开程序,需要额外关闭)
process.destroyForcibly();
}
}
private static void printStreamString(Process finalProcess) {
// 新建线程接收子进程输出信息(INFO)
new Thread(() -> {
try {
InputStreamReader inputStreamReaderINFO = new InputStreamReader(finalProcess.getInputStream());
BufferedReader bufferedReaderINFO = new BufferedReader(inputStreamReaderINFO);
String lineStr;
while ((lineStr = bufferedReaderINFO.readLine()) != null) {
System.out.println("INFO > " + lineStr);
}
} catch (IOException exception) {
exception.printStackTrace();
}
}).start();
// 新建线程接收子进程输出信息(ERROR)
new Thread(() -> {
try {
InputStreamReader inputStreamReaderERROR = new InputStreamReader(finalProcess.getErrorStream());
BufferedReader bufferedReaderERROR = new BufferedReader(inputStreamReaderERROR);
String lineStr;
while ((lineStr = bufferedReaderERROR.readLine()) != null) {
System.out.println("ERROR > " + lineStr);
}
} catch (IOException exception) {
exception.printStackTrace();
}
}).start();
}