2024-03-13
原文作者:吴声子夜歌 原文地址: https://blog.csdn.net/cold___play/article/details/133965960

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
                }
              }
            }
          }
        }
      }
    }
阅读全文