Java 执行 curl 命令获取 ES Response

Java ProcessBuilder 执行 curl 命令获取 ElasticSearch 数据。

部分 curl 命令参数说明

参数说明
-XGET指定 GET 命令
–tlsv1.2指定通信协议为TLSv1.2
–negotiate使用HTTP身份验证
-k允许不使用证书到SSL站点
-u设置服务器的用户和密码
-H自定义头信息传递给服务器
-dHTTP 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();
    }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值