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 }
人生还有意义。那一定是还在找存在的理由