【问题标题】:What can i do to make a http put request from springboot to a URL我该怎么做才能从 springboot 向 URL 发出 http put 请求
【发布时间】:2022-01-21 10:13:19
【问题描述】:

我想向在端口 9200 上运行的弹性搜索服务器发出一个 http put 请求,以在创建索引时初始设置其映射,明确地说,我想通过 Spring Boot 而不是通过 curl 来执行此操作。 put 请求应该有一个 JSON 格式的正文,其中包含映射的属性。

【问题讨论】:

  • 看看org.springframework.web.client.RestTemplate,它是一个高级REST接口

标签: java spring spring-boot elasticsearch


【解决方案1】:

您可以使用RestTemplate

这是我尝试过的方法,为了测试,我制作了简单的 get api,它创建一个索引并在之后更新它。

@GetMapping
    public Map<String, Object> updateEsMapping() throws JsonProcessingException {
        //Create mapping index
        final Map<String, Object> request =
                Map.of("properties", Map.of(
                        "id", Map.of("type", "keyword"),
                        "name", Map.of("type", "keyword"),
                        "date", Map.of("type", "date")
                ));
        //Compose  json header
        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        //Create entity
        final HttpEntity<String> entity = new HttpEntity<String>(objectMapper.writeValueAsString(request), headers);

        //es constants
        final String host = "http://localhost:9200/";
        final String indexName = "raw-sample-document-creation/";
        final String mapping = "_mapping/";

        //First create index
        restTemplate.put(host + indexName, null);

        //Update mapping
        ResponseEntity<String> exchange = restTemplate.exchange(host + indexName + mapping, HttpMethod.PUT, entity, String.class);
        
        
        return Map.of("status", "ok", "request", exchange.getBody()
                .replace("\n", "")
                .replace("\r", "")
        );
    }

您可以在此处探索更多标准方法 https://docs.spring.io/spring-data/elasticsearch/docs/current/reference/html/#elasticsearch.clients

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多