Java 访问Rest API
Elasticsearch提供Rest API,所以可以直接直接使用 HTTP 请求,去操作 Es。HTTP 请求工具,可以使用 Java 自带的 HttpUrlConnection,也可以使用一些 HTTP 请求库,例如 HttpClient、OKHttp、Spring 中的 RestTemplate 都可以。这种方式有一个弊端,就是要自己组装请求参数,自己去解析响应的 JSON。
1、原生Java访问Rest API
在Java中,可以使用java.net包下的URLConnection类来发送HTTP请求。
//java原生,手动认证后调用_count接口
@Test
public void java_auh() throws IOException {
String username = "elastic";
String password = "123456";
//构造Authorization
String auth = username + ":" + password;
String encodeAuth = Base64.getEncoder().encodeToString(auth.getBytes());
String authHeader = "Basic " + encodeAuth;
URL url = new URL("http://localhost:9200/bank/_count?pretty=true");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", authHeader);
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
{
"count" : 1000,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
}
}
2、HttpClient访问Rest API
示例:访问_search接口
//basic auth手动编码认证,调用_search接口
@Test
public void httpclient_auth1() throws IOException {
String username = "elastic";
String password = "123456";
//构造Authorization
String auth = username + ":" + password;
String encodeAuth = Base64.getEncoder().encodeToString(auth.getBytes());
String authHeader = "Basic " + encodeAuth;
CloseableHttpClient client = HttpClients.custom().build();
HttpGet httpGet = new HttpGet("http://localhost:9200/bank/_search");
httpGet.setHeader("Authorization", authHeader);
CloseableHttpResponse response = client.execute(httpGet);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//获取实体内容
HttpEntity entity = response.getEntity();
//注意设置编码
String entityString = EntityUtils.toString(entity, "utf8");
//输出内容
System.out.println(entityString);
EntityUtils.consume(response.getEntity());//消耗实体
}
}
{"took":8,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":1000,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"bank","_type":"_doc","_id":"1","_score":1.0,"_source":{"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}},{"_index":"bank","_type":"_doc","_id":"6","_score":1.0,"_source":{"account_number":6,"balance":5686,"firstname":"Hattie","lastname":"Bond","age":36,"gender":"M","address":"671 Bristol Street","employer":"Netagy","email":"hattiebond@netagy.com","city":"Dante","state":"TN"}},{"_index":"bank","_type":"_doc","_id":"13","_score":1.0,"_source":{"account_number":13,"balance":32838,"firstname":"Nanette","lastname":"Bates","age":28,"gender":"F","address":"789 Madison Street","employer":"Quility","email":"nanettebates@quility.com","city":"Nogal","state":"VA"}},{"_index":"bank","_type":"_doc","_id":"18","_score":1.0,"_source":{"account_number":18,"balance":4180,"firstname":"Dale","lastname":"Adams","age":33,"gender":"M","address":"467 Hutchinson Court","employer":"Boink","email":"daleadams@boink.com","city":"Orick","state":"MD"}},{"_index":"bank","_type":"_doc","_id":"20","_score":1.0,"_source":{"account_number":20,"balance":16418,"firstname":"Elinor","lastname":"Ratliff","age":36,"gender":"M","address":"282 Kings Place","employer":"Scentric","email":"elinorratliff@scentric.com","city":"Ribera","state":"WA"}},{"_index":"bank","_type":"_doc","_id":"25","_score":1.0,"_source":{"account_number":25,"balance":40540,"firstname":"Virginia","lastname":"Ayala","age":39,"gender":"F","address":"171 Putnam Avenue","employer":"Filodyne","email":"virginiaayala@filodyne.com","city":"Nicholson","state":"PA"}},{"_index":"bank","_type":"_doc","_id":"32","_score":1.0,"_source":{"account_number":32,"balance":48086,"firstname":"Dillard","lastname":"Mcpherson","age":34,"gender":"F","address":"702 Quentin Street","employer":"Quailcom","email":"dillardmcpherson@quailcom.com","city":"Veguita","state":"IN"}},{"_index":"bank","_type":"_doc","_id":"37","_score":1.0,"_source":{"account_number":37,"balance":18612,"firstname":"Mcgee","lastname":"Mooney","age":39,"gender":"M","address":"826 Fillmore Place","employer":"Reversus","email":"mcgeemooney@reversus.com","city":"Tooleville","state":"OK"}},{"_index":"bank","_type":"_doc","_id":"44","_score":1.0,"_source":{"account_number":44,"balance":34487,"firstname":"Aurelia","lastname":"Harding","age":37,"gender":"M","address":"502 Baycliff Terrace","employer":"Orbalix","email":"aureliaharding@orbalix.com","city":"Yardville","state":"DE"}},{"_index":"bank","_type":"_doc","_id":"49","_score":1.0,"_source":{"account_number":49,"balance":29104,"firstname":"Fulton","lastname":"Holt","age":23,"gender":"F","address":"451 Humboldt Street","employer":"Anocha","email":"fultonholt@anocha.com","city":"Sunriver","state":"RI"}}]}}
示例:访问_analyze接口
//使用CredentialsProvider认证,调用 _analyze接口
@Test
public void httpclient_auth2() throws IOException {
String url = "http://localhost:9200/_analyze?pretty=true";
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("DataEncoding", "UTF-8");
JSONObject object = new JSONObject();
object.put("analyzer","ik_smart");
object.put("text", "我是中国人");
httpPost.setEntity(new StringEntity(object.toString(), "UTF-8"));
// 加es身份认证
HttpHost targetHost = new HttpHost("192.168.1.1", 9200, "http");
//设置账号密码
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("elastic", "123456"));
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(targetHost, basicAuth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
CloseableHttpResponse response = httpClient.execute(httpPost, context);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
//获取实体内容
HttpEntity entity = response.getEntity();
//注意设置编码
String entityString = EntityUtils.toString(entity, "utf8");
//输出内容
System.out.println(entityString);
EntityUtils.consume(response.getEntity());//消耗实体
}
}
{
"tokens" : [
{
"token" : "我",
"start_offset" : 0,
"end_offset" : 1,
"type" : "CN_CHAR",
"position" : 0
},
{
"token" : "是",
"start_offset" : 1,
"end_offset" : 2,
"type" : "CN_CHAR",
"position" : 1
},
{
"token" : "中国人",
"start_offset" : 2,
"end_offset" : 5,
"type" : "CN_WORD",
"position" : 2
}
]
}
3、使用RestTemplate访问Rest API
@SpringBootApplication
public class AppApplication {
public static void main(String[] args) {
SpringApplication.run(AppApplication.class, args);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {AppApplication.class})
public class RestTemplateTest {
@Autowired
RestTemplate restTemplate;
@Test
public void restTemplate_auth() {
String username = "elastic";
String password = "123456";
//构造Authorization
String auth = username + ":" + password;
String encodeAuth = Base64.getEncoder().encodeToString(auth.getBytes());
String authHeader = "Basic " + encodeAuth;
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", authHeader);
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange("http://localhost:9200/bank/_mappings?pretty=true",
HttpMethod.GET,
entity,
String.class);
if (response.getStatusCode() == HttpStatus.OK){
System.out.println(response.getBody());
}
}
}
{
"bank" : {
"mappings" : {
"properties" : {
"account_number" : {
"type" : "long"
},
"address" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"age" : {
"type" : "long"
},
"balance" : {
"type" : "long"
},
"city" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"email" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"employer" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"firstname" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"gender" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"lastname" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"state" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
}
}
}
Java 面试宝典是大明哥全力打造的 Java 精品面试题,它是一份靠谱、强大、详细、经典的 Java 后端面试宝典。它不仅仅只是一道道面试题,而是一套完整的 Java 知识体系,一套你 Java 知识点的扫盲贴。
它的内容包括:
- 大厂真题:Java 面试宝典里面的题目都是最近几年的高频的大厂面试真题。
- 原创内容:Java 面试宝典内容全部都是大明哥原创,内容全面且通俗易懂,回答部分可以直接作为面试回答内容。
- 持续更新:一次购买,永久有效。大明哥会持续更新 3+ 年,累计更新 1000+,宝典会不断迭代更新,保证最新、最全面。
- 覆盖全面:本宝典累计更新 1000+,从 Java 入门到 Java 架构的高频面试题,实现 360° 全覆盖。
- 不止面试:内容包含面试题解析、内容详解、知识扩展,它不仅仅只是一份面试题,更是一套完整的 Java 知识体系。
- 宝典详情:https://www.yuque.com/chenssy/sike-java/xvlo920axlp7sf4k
- 宝典总览:https://www.yuque.com/chenssy/sike-java/yogsehzntzgp4ly1
- 宝典进展:https://www.yuque.com/chenssy/sike-java/en9ned7loo47z5aw
目前 Java 面试宝典累计更新 400+ 道,总字数 42w+。大明哥还在持续更新中,下图是大明哥在 2024-12 月份的更新情况:
想了解详情的小伙伴,扫描下面二维码加大明哥微信【daming091】咨询
同时,大明哥也整理一套目前市面最常见的热点面试题。微信搜[大明哥聊 Java]或扫描下方二维码关注大明哥的原创公众号[大明哥聊 Java] ,回复【面试题】 即可免费领取。