java 连接带认证的 elasticsearch

1.使用elasticsearch 官方提供客户端:org.elasticsearch.client.RestClientBuilder

pom.xml 添加依赖:

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>7.6.2</version>
</dependency>

java 代码:

 

复制代码
 1         RestClientBuilder builder = RestClient.builder(new HttpHost(
 2                 "localhost",
 3                 9200,
 4                 "http")
 5         );
// 此处添加认证 header 值为 Base64编码后的 user:password
6 Header[] myheaders = { 7 new BasicHeader("Authorization","Basic YWJkaV9hZG1pbjpBRkVEb3ZNclRSeGdjcUpjRW5GREJPcUxIYUdLVHRkOXM5d0Uxd3NpVnI5TVZDenc=") 8 }; 9 builder.setDefaultHeaders(myheaders);
10 RestClient client = builder.build(); 11 String index = "secvisual.system_state"; 12 String query = "{\"query\":{\"match_all\":{}}}"; 13 try { 14 String searchIndex = String.format("/%s/_search?ignore_unavailable=%s", index, true); 15 Request request = new Request("GET", searchIndex); 16 request.setJsonEntity(query); 17 18 Response response = client.performRequest(request); 19 if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { 20 System.out.println("query failed!"); 21 } 22 23 String body = EntityUtils.toString(response.getEntity()); 24 System.out.println("query success, reuslt:" + body); 25 } catch (Exception e) { 26 System.out.println(e); 27 } 28 finally { 29 client.close(); 30 }
复制代码

 

posted @   G1733  阅读(916)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
历史上的今天:
2020-05-18 文件读写控制库 fcntl
点击右上角即可分享
微信分享提示