类org.apache.http.nio.entity.NStringEntity源码实例Demo

下面列出了怎么用org.apache.http.nio.entity.NStringEntity的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: presto   文件: TestPasswordAuthentication.java
@Test
public void test()
        throws IOException
{
    String json = new ObjectMapper().writeValueAsString(ImmutableMap.<String, Object>builder()
            .put("value", 42L)
            .build());

    client.getLowLevelClient()
            .performRequest(
                    "POST",
                    "/test/_doc?refresh",
                    ImmutableMap.of(),
                    new NStringEntity(json, ContentType.APPLICATION_JSON),
                    new BasicHeader("Authorization", format("Basic %s", Base64.encodeAsString(format("%s:%s", USER, PASSWORD).getBytes(StandardCharsets.UTF_8)))));

    assertThat(assertions.query("SELECT * FROM test"))
            .matches("VALUES BIGINT '42'");
}
 
源代码2 项目: ProjectStudy   文件: LowLevelRestController.java
/**
 * 添加ES对象, Book的ID就是ES中存储的Document的ID,ES的POST和PUT可以看下面这个文章
 * https://blog.csdn.net/z457181562/article/details/93470152
 *
 * @param bookDto
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/8 17:46
 */
@PostMapping("/book")
public ResponseBean add(@RequestBody BookDto bookDto) throws IOException {
    // Endpoint直接指定为Index/Type的形式
    /*Request request = new Request("POST", new StringBuilder("/book/book/").toString());*/
    // 防重复新增数据
    bookDto.setId(System.currentTimeMillis());
    Request request = new Request("PUT", new StringBuilder("/book/book/")
            .append(bookDto.getId()).append("/_create").toString());
    // 设置其他一些参数比如美化Json
    request.addParameter("pretty", "true");
    // 设置请求体并指定ContentType,如果不指定会乱码
    request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON));
    // 发送HTTP请求
    Response response = restClient.performRequest(request);
    // 获取响应体
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "添加成功", JSON.parseObject(responseBody));
}
 
源代码3 项目: ProjectStudy   文件: LowLevelRestController.java
/**
 * 根据Id更新Book,ES的POST和PUT可以看下面这个文章
 *
 * https://blog.csdn.net/z457181562/article/details/93470152
 * @param bookDto
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/9 10:04
 */
@PutMapping("/book")
public ResponseBean update(@RequestBody BookDto bookDto) throws IOException {
    // 构造HTTP请求
    /*Request request = new Request("POST", new StringBuilder("/book/book/")
            .append(bookDto.getId()).append("/_update").toString());*/
    Request request = new Request("PUT", new StringBuilder("/book/book/")
            .append(bookDto.getId()).toString());
    // 设置其他一些参数比如美化Json
    request.addParameter("pretty", "true");
    /*// 将数据丢进去,这里一定要外包一层'doc',否则内部不能识别
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("doc", new JSONObject(bookDto));*/
    // 设置请求体并指定ContentType,如果不指定会乱码
    request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON));
    // 执行HTTP请求
    Response response = restClient.performRequest(request);
    // 获取返回的内容
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "更新成功", JSON.parseObject(responseBody));
}
 
源代码4 项目: ProjectStudy   文件: LowLevelRestController.java
/**
   * 使用脚本更新Name
   *
   * @param id
* @param bookDto
   * @return org.springframework.http.ResponseEntity<java.lang.String>
   * @throws IOException
   * @author wliduo[[email protected]]
   * @date 2019/8/9 11:37
   */
  @PutMapping("/book/{id}")
  public ResponseEntity<String> update2(@PathVariable("id") String id, @RequestBody BookDto bookDto) throws IOException {
      // 构造HTTP请求
      Request request = new Request("POST", new StringBuilder("/book/book/")
              .append(id).append("/_update").toString());
      // 设置其他一些参数比如美化Json
      request.addParameter("pretty", "true");
      JSONObject jsonObject = new JSONObject();
      // 创建脚本语言,如果是字符变量,必须加单引号
      StringBuilder op1 = new StringBuilder("ctx._source.name=").append("'" + bookDto.getName() + "'");
      jsonObject.put("script", op1);
      request.setEntity(new NStringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
      // 执行HTTP请求
      Response response = restClient.performRequest(request);
      // 获取返回的内容
      String responseBody = EntityUtils.toString(response.getEntity());
      return new ResponseEntity<>(responseBody, HttpStatus.OK);
  }
 
源代码5 项目: ProjectStudy   文件: LowLevelRestController.java
/**
 * 添加ES对象, Book的ID就是ES中存储的Document的ID,ES的POST和PUT可以看下面这个文章
 * https://blog.csdn.net/z457181562/article/details/93470152
 *
 * @param bookDto
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/8 17:46
 */
@PostMapping("/book")
public ResponseBean add(@RequestBody BookDto bookDto) throws IOException {
    // Endpoint直接指定为Index/Type的形式
    /*Request request = new Request("POST", new StringBuilder("/book/book/").toString());*/
    // 防重复新增数据
    bookDto.setId(System.currentTimeMillis());
    Request request = new Request("PUT", new StringBuilder("/book/book/")
            .append(bookDto.getId()).append("/_create").toString());
    // 设置其他一些参数比如美化Json
    request.addParameter("pretty", "true");
    // 设置请求体并指定ContentType,如果不指定会乱码
    request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON));
    // 发送HTTP请求
    Response response = restClient.performRequest(request);
    // 获取响应体
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "添加成功", JSON.parseObject(responseBody));
}
 
源代码6 项目: ProjectStudy   文件: LowLevelRestController.java
/**
 * 根据Id更新Book,ES的POST和PUT可以看下面这个文章
 *
 * https://blog.csdn.net/z457181562/article/details/93470152
 * @param bookDto
 * @return org.springframework.http.ResponseEntity<java.lang.String>
 * @throws IOException
 * @author wliduo[[email protected]]
 * @date 2019/8/9 10:04
 */
@PutMapping("/book")
public ResponseBean update(@RequestBody BookDto bookDto) throws IOException {
    // 构造HTTP请求
    /*Request request = new Request("POST", new StringBuilder("/book/book/")
            .append(bookDto.getId()).append("/_update").toString());*/
    Request request = new Request("PUT", new StringBuilder("/book/book/")
            .append(bookDto.getId()).toString());
    // 设置其他一些参数比如美化Json
    request.addParameter("pretty", "true");
    /*// 将数据丢进去,这里一定要外包一层'doc',否则内部不能识别
    JSONObject jsonObject = new JSONObject();
    jsonObject.put("doc", new JSONObject(bookDto));*/
    // 设置请求体并指定ContentType,如果不指定会乱码
    request.setEntity(new NStringEntity(JSONObject.toJSONString(bookDto), ContentType.APPLICATION_JSON));
    // 执行HTTP请求
    Response response = restClient.performRequest(request);
    // 获取返回的内容
    String responseBody = EntityUtils.toString(response.getEntity());
    return new ResponseBean(HttpStatus.OK.value(), "更新成功", JSON.parseObject(responseBody));
}
 
源代码7 项目: ProjectStudy   文件: LowLevelRestController.java
/**
   * 使用脚本更新Name
   *
   * @param id
* @param bookDto
   * @return org.springframework.http.ResponseEntity<java.lang.String>
   * @throws IOException
   * @author wliduo[[email protected]]
   * @date 2019/8/9 11:37
   */
  @PutMapping("/book/{id}")
  public ResponseEntity<String> update2(@PathVariable("id") String id, @RequestBody BookDto bookDto) throws IOException {
      // 构造HTTP请求
      Request request = new Request("POST", new StringBuilder("/book/book/")
              .append(id).append("/_update").toString());
      // 设置其他一些参数比如美化Json
      request.addParameter("pretty", "true");
      JSONObject jsonObject = new JSONObject();
      // 创建脚本语言,如果是字符变量,必须加单引号
      StringBuilder op1 = new StringBuilder("ctx._source.name=").append("'" + bookDto.getName() + "'");
      jsonObject.put("script", op1);
      request.setEntity(new NStringEntity(jsonObject.toString(), ContentType.APPLICATION_JSON));
      // 执行HTTP请求
      Response response = restClient.performRequest(request);
      // 获取返回的内容
      String responseBody = EntityUtils.toString(response.getEntity());
      return new ResponseEntity<>(responseBody, HttpStatus.OK);
  }
 
源代码8 项目: griffin   文件: MetricStoreImpl.java
private HttpEntity getHttpEntityForSearch(String metricName, int from, int
    size, long tmst)
    throws JsonProcessingException {
    Map<String, Object> map = new HashMap<>();
    Map<String, Object> queryParam = new HashMap<>();
    Map<String, Object> termQuery = Collections.singletonMap("name.keyword",
        metricName);
    queryParam.put("filter", Collections.singletonMap("term", termQuery));
    Map<String, Object> sortParam = Collections
        .singletonMap("tmst", Collections.singletonMap("order",
            "desc"));
    map.put("query", Collections.singletonMap("bool", queryParam));
    map.put("sort", sortParam);
    map.put("from", from);
    map.put("size", size);
    return new NStringEntity(JsonUtil.toJson(map),
        ContentType.APPLICATION_JSON);
}
 
源代码9 项目: beam   文件: ElasticsearchIO.java
@Override
public boolean advance() throws IOException {
  if (batchIterator.hasNext()) {
    current = batchIterator.next();
    return true;
  } else {
    String requestBody =
        String.format(
            "{\"scroll\" : \"%s\",\"scroll_id\" : \"%s\"}",
            source.spec.getScrollKeepalive(), scrollId);
    HttpEntity scrollEntity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
    Request request = new Request("GET", "/_search/scroll");
    request.addParameters(Collections.emptyMap());
    request.setEntity(scrollEntity);
    Response response = restClient.performRequest(request);
    JsonNode searchResult = parseResponse(response.getEntity());
    updateScrollId(searchResult);
    return readNextBatchAndReturnFirstDocument(searchResult);
  }
}
 
源代码10 项目: beam   文件: ElasticsearchIO.java
@Override
public void close() throws IOException {
  // remove the scroll
  String requestBody = String.format("{\"scroll_id\" : [\"%s\"]}", scrollId);
  HttpEntity entity = new NStringEntity(requestBody, ContentType.APPLICATION_JSON);
  try {
    Request request = new Request("DELETE", "/_search/scroll");
    request.addParameters(Collections.emptyMap());
    request.setEntity(entity);
    restClient.performRequest(request);
  } finally {
    if (restClient != null) {
      restClient.close();
    }
  }
}
 
源代码11 项目: skywalking   文件: ElasticSearchClient.java
public boolean createTemplate(String indexName, Map<String, Object> settings,
                              Map<String, Object> mapping) throws IOException {
    indexName = formatIndexName(indexName);

    String[] patterns = new String[] {indexName + "-*"};

    Map<String, Object> aliases = new HashMap<>();
    aliases.put(indexName, new JsonObject());

    Map<String, Object> template = new HashMap<>();
    template.put("index_patterns", patterns);
    template.put("aliases", aliases);
    template.put("settings", settings);
    template.put("mappings", mapping);

    HttpEntity entity = new NStringEntity(new Gson().toJson(template), ContentType.APPLICATION_JSON);

    Response response = client.getLowLevelClient()
                              .performRequest(
                                  HttpPut.METHOD_NAME, "/_template/" + indexName, Collections.emptyMap(), entity);
    return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK;
}
 
@BeforeEach
public void setup() throws Exception {
    client = ElasticsearchClientFactory.create(globals());
    retrieveDao = new ElasticsearchRetrieveLatestDao(client);
    writer = new ElasticsearchBulkDocumentWriter<>(client)
            .withRefreshPolicy(WriteRequest.RefreshPolicy.WAIT_UNTIL);

    // add bro template
    JSONObject broTemplate = JSONUtils.INSTANCE.load(new File(broTemplatePath), JSONObject.class);
    String broTemplateJson = JSONUtils.INSTANCE.toJSON(broTemplate, true);
    HttpEntity broEntity = new NStringEntity(broTemplateJson, ContentType.APPLICATION_JSON);
    Response response = client
            .getLowLevelClient()
            .performRequest("PUT", "/_template/bro_template", Collections.emptyMap(), broEntity);
    assertThat(response.getStatusLine().getStatusCode(), CoreMatchers.equalTo(200));
}
 
@Test(timeout = 60000L)
public void testAll() throws Exception {
    HttpHost host = new HttpHost(HOST, HTTP_PORT, "http");
    RestClient client = RestClient.builder(new HttpHost[]{ host }).build();
    HttpEntity entity = new NStringEntity("{\"foo\":\"bar\"}", ContentType.APPLICATION_JSON);
    Request request = new Request("POST", "/test/_doc/");
    request.setEntity(entity);
    client.performRequest(request);

    MockDispatcher dispatcher = new MockDispatcher();
    ElasticsearchCollector collector = new ElasticsearchCollector();
    collector.setDispatcher(dispatcher);
    Hashtable<String, Object> configuration = new Hashtable<>();
    configuration.put("addresses", "http://localhost:" + HTTP_PORT);
    configuration.put("index", "test");
    collector.activate(configuration);

    collector.run();

    Assert.assertEquals(1, dispatcher.postedEvents.size());
    Assert.assertEquals("elasticsearch", dispatcher.postedEvents.get(0).getProperty("type"));
    Assert.assertEquals("decanter/collect/elasticsearch", dispatcher.postedEvents.get(0).getTopic());
}
 
源代码14 项目: jframe   文件: WeikePath.java
private void bulkIndexMember(List<?> memList) throws Exception {
    StringBuilder buf = new StringBuilder(1024);
    for (Object mem : memList) {
        buf.append("{\"index\": {}}");
        buf.append("\n");
        buf.append(Gson.toJson(mem));
        buf.append("\n");
    }

    long startTime = System.currentTimeMillis();
    RestClient client = Plugin.client;

    HttpEntity entity = new NStringEntity(buf.toString(), ContentType.APPLICATION_JSON);

    Response indexResponse = client.performRequest("POST", "/weike/member/_bulk",
            Collections.<String, String>emptyMap(), entity);

    if (LOG.isDebugEnabled()) {
        LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime);
        LOG.debug("indexResponse {}", indexResponse.toString());
    }
}
 
源代码15 项目: jframe   文件: WeikePath.java
private void indexMember(String sellerId, Object mem) throws IOException {
    if (sellerId == null)
        sellerId = "";

    long startTime = System.currentTimeMillis();

    RestClient client = Plugin.client;
    String json = Gson.toJson(mem);

    HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
    String path = "/weike/member";
    if (!"".equals(sellerId)) {
        path += "?routing=" + sellerId;
    }
    Response indexResponse = client.performRequest("POST", path, Collections.<String, String>emptyMap(), entity);

    if (LOG.isDebugEnabled()) {
        LOG.debug("indexMember {}ms", System.currentTimeMillis() - startTime);
        LOG.debug("indexResponse {}", indexResponse.toString());
    }
}
 
源代码16 项目: jframe   文件: TestQuery.java
@Test
@Ignore
public void testSearch() throws Exception {
    // JsonObject json = new JsonObject();
    // json.addProperty("from", "0");
    // json.addProperty("size", "10");
    // json.addProperty("explain", true);
    // JsonObject query = new JsonObject();
    // query.add
    // json.add("query", query);
    String json = "{\"explain\":false,\"from\":0,\"size\":1,\"query\":{\"range\":{\"tradeAmount\":{\"gte\":10,\"lte\":2000}}}}";

    long startTime = System.currentTimeMillis();
    HttpEntity entity = new NStringEntity(json, ContentType.APPLICATION_JSON);
    Response response = client.performRequest("GET", "/weike/member/_search", Collections.singletonMap("pretty", "true"), entity);
    LOG.info("search-{} {}ms", EntityUtils.toString(response.getEntity()), System.currentTimeMillis() - startTime);
}
 
源代码17 项目: nifi   文件: ElasticSearchClientServiceImpl.java
private Response runQuery(String endpoint, String query, String index, String type) {
    StringBuilder sb = new StringBuilder()
        .append("/")
        .append(index);
    if (type != null && !type.equals("")) {
        sb.append("/")
        .append(type);
    }

    sb.append(String.format("/%s", endpoint));

    HttpEntity queryEntity = new NStringEntity(query, ContentType.APPLICATION_JSON);

    try {
        return client.performRequest("POST", sb.toString(), Collections.emptyMap(), queryEntity);
    } catch (Exception e) {
        throw new ElasticsearchError(e);
    }
}
 
源代码18 项目: nifi   文件: ElasticSearchClientServiceImpl.java
@Override
public DeleteOperationResponse deleteById(String index, String type, List<String> ids) {
    try {
        StringBuilder sb = new StringBuilder();
        for (int idx = 0; idx < ids.size(); idx++) {
            String header = buildBulkHeader("delete", index, type, ids.get(idx));
            sb.append(header).append("\n");
        }
        HttpEntity entity = new NStringEntity(sb.toString(), ContentType.APPLICATION_JSON);
        StopWatch watch = new StopWatch();
        watch.start();
        Response response = client.performRequest("POST", "/_bulk", Collections.emptyMap(), entity);
        watch.stop();

        if (getLogger().isDebugEnabled()) {
            getLogger().debug(String.format("Response for bulk delete: %s",
                    IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8)));
        }

        DeleteOperationResponse dor = new DeleteOperationResponse(watch.getDuration(TimeUnit.MILLISECONDS));

        return dor;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
 
源代码19 项目: presto   文件: BaseElasticsearchSmokeTest.java
private void createIndex(String indexName, @Language("JSON") String properties)
        throws IOException
{
    String mappings = indexMapping(properties);
    client.getLowLevelClient()
            .performRequest("PUT", "/" + indexName, ImmutableMap.of(), new NStringEntity(mappings, ContentType.APPLICATION_JSON));
}
 
源代码20 项目: ProjectStudy   文件: LowLevelRestController.java
/**
   * 分词分页查询列表
   *
   * @param page
* @param rows
* @param keyword
   * @return com.example.common.ResponseBean
   * @author wliduo[[email protected]]
   * @date 2019/8/9 15:32
   */
  @GetMapping("/book")
  public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer rows,
                                  String keyword) {
      Request request = new Request("POST", new StringBuilder("/_search").toString());
      // 添加Json返回优化
      request.addParameter("pretty", "true");
      // 拼接查询Json
      IndexRequest indexRequest = new IndexRequest();
      XContentBuilder builder = null;
      Response response = null;
      String responseBody = null;
      try {
          builder = JsonXContent.contentBuilder()
                  .startObject()
                  .startObject("query")
                  .startObject("multi_match")
                  .field("query", keyword)
                  .array("fields", new String[]{"name", "desc"})
                  .endObject()
                  .endObject()
                  .startObject("sort")
                  .startObject("id")
                  .field("order", "desc")
                  .endObject()
                  .endObject()
                  .endObject();
          indexRequest.source(builder);
          // 设置请求体并指定ContentType,如果不指定会乱码
          request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON));
          // 执行HTTP请求
          response = restClient.performRequest(request);
          responseBody = EntityUtils.toString(response.getEntity());
      } catch (IOException e) {
          return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
      }
      return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
  }
 
源代码21 项目: ProjectStudy   文件: LowLevelRestController.java
/**
   * 分词分页查询列表
   *
   * @param page
* @param rows
* @param keyword
   * @return com.example.common.ResponseBean
   * @author wliduo[[email protected]]
   * @date 2019/8/9 15:32
   */
  @GetMapping("/book")
  public ResponseBean getBookList(@RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer rows,
                                  String keyword) {
      Request request = new Request("POST", new StringBuilder("/_search").toString());
      // 添加Json返回优化
      request.addParameter("pretty", "true");
      // 拼接查询Json
      IndexRequest indexRequest = new IndexRequest();
      XContentBuilder builder = null;
      Response response = null;
      String responseBody = null;
      try {
          builder = JsonXContent.contentBuilder()
                  .startObject()
                  .startObject("query")
                  .startObject("multi_match")
                  .field("query", keyword)
                  .array("fields", new String[]{"name", "desc"})
                  .endObject()
                  .endObject()
                  .startObject("sort")
                  .startObject("id")
                  .field("order", "desc")
                  .endObject()
                  .endObject()
                  .endObject();
          indexRequest.source(builder);
          // 设置请求体并指定ContentType,如果不指定会乱码
          request.setEntity(new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON));
          // 执行HTTP请求
          response = restClient.performRequest(request);
          responseBody = EntityUtils.toString(response.getEntity());
      } catch (IOException e) {
          return new ResponseBean(HttpStatus.NOT_FOUND.value(), "can not found the book by your id", null);
      }
      return new ResponseBean(HttpStatus.OK.value(), "查询成功", JSON.parseObject(responseBody));
  }
 
public void testSearchAnomalyDetector() throws Exception {
    AnomalyDetector detector = createRandomAnomalyDetector(true, true);
    SearchSourceBuilder search = (new SearchSourceBuilder()).query(QueryBuilders.termQuery("_id", detector.getDetectorId()));

    updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, false);

    Exception ex = expectThrows(
        ResponseException.class,
        () -> TestHelpers
            .makeRequest(
                client(),
                "GET",
                TestHelpers.AD_BASE_DETECTORS_URI + "/_search",
                ImmutableMap.of(),
                new NStringEntity(search.toString(), ContentType.APPLICATION_JSON),
                null
            )
    );
    assertThat(ex.getMessage(), containsString(CommonErrorMessages.DISABLED_ERR_MSG));

    updateClusterSettings(EnabledSetting.AD_PLUGIN_ENABLED, true);

    Response searchResponse = TestHelpers
        .makeRequest(
            client(),
            "GET",
            TestHelpers.AD_BASE_DETECTORS_URI + "/_search",
            ImmutableMap.of(),
            new NStringEntity(search.toString(), ContentType.APPLICATION_JSON),
            null
        );
    assertEquals("Search anomaly detector failed", RestStatus.OK, restStatus(searchResponse));
}
 
源代码23 项目: anomaly-detection   文件: TestHelpers.java
public static Response makeRequest(
    RestClient client,
    String method,
    String endpoint,
    Map<String, String> params,
    String jsonEntity,
    List<Header> headers
) throws IOException {
    HttpEntity httpEntity = Strings.isBlank(jsonEntity) ? null : new NStringEntity(jsonEntity, ContentType.APPLICATION_JSON);
    return makeRequest(client, method, endpoint, params, httpEntity, headers);
}
 
源代码24 项目: java-specialagent   文件: ElasticsearchITest.java
private static void runRestClient() throws IOException, InterruptedException {
  try (final RestClient restClient = RestClient.builder(new HttpHost("localhost", HTTP_PORT, "http")).build()) {
    final HttpEntity entity = new NStringEntity(
      "{\n" +
      "    \"user\": \"user\",\n" +
      "    \"post_date\": \"2009-11-15T14:12:12\",\n" +
      "    \"message\": \"trying out Elasticsearch\"\n" +
      "}", ContentType.APPLICATION_JSON);

    final Request request1 = new Request("PUT", "/twitter/tweet/1");
    request1.setEntity(entity);

    final Response indexResponse = restClient.performRequest(request1);
    System.out.println(indexResponse);

    final Request request2 = new Request("PUT", "/twitter/tweet/2");
    request2.setEntity(entity);

    final CountDownLatch latch = new CountDownLatch(1);
    restClient.performRequestAsync(request2, new ResponseListener() {
      @Override
      public void onSuccess(final Response response) {
        latch.countDown();
      }

      @Override
      public void onFailure(final Exception e) {
        latch.countDown();
      }
    });

    latch.await(30, TimeUnit.SECONDS);
  }
}
 
源代码25 项目: Groza   文件: ElasticsearchAuditLogSink.java
@Override
public void logAction(AuditLog auditLogEntry) {
    String jsonContent = createElasticJsonRecord(auditLogEntry);

    HttpEntity entity = new NStringEntity(
            jsonContent,
            ContentType.APPLICATION_JSON);

    restClient.performRequestAsync(
            HttpMethod.POST.name(),
            String.format("/%s/%s", getIndexName(auditLogEntry.getTenantId()), INDEX_TYPE),
            Collections.emptyMap(),
            entity,
            responseListener);
}
 
源代码26 项目: newblog   文件: HttpHelper.java
public String doPost(String url, String data, String charset) {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    log.info(" post url=" + url);
    try {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new NStringEntity(data, charset));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            httpPost.abort();
            throw new RuntimeException("HttpClient,error status code :" + statusCode);
        }
        HttpEntity entity = response.getEntity();
        String result = null;
        if (entity != null) {
            result = EntityUtils.toString(entity, charset);
        }
        EntityUtils.consume(entity);
        response.close();
        return result;
    } catch (Exception e) {
        log.error("to request addr=" + url + ", " + e.getMessage());
        e.printStackTrace();
    }
    return null;
}
 
源代码27 项目: griffin   文件: MetricStoreImpl.java
@Override
public ResponseEntity<?> addMetricValues(List<MetricValue> metricValues)
    throws IOException {
    String bulkRequestBody = getBulkRequestBody(metricValues);
    HttpEntity entity = new NStringEntity(bulkRequestBody,
        ContentType.APPLICATION_JSON);
    Response response = client.performRequest("POST", urlPost,
        Collections.emptyMap(), entity);
    return getResponseEntityFromResponse(response);
}
 
源代码28 项目: griffin   文件: MetricStoreImpl.java
@Override
public ResponseEntity<?> deleteMetricValues(String metricName) throws
    IOException {
    Map<String, Object> param = Collections.singletonMap("query",
        Collections.singletonMap("term",
            Collections.singletonMap("name.keyword", metricName)));
    HttpEntity entity = new NStringEntity(
        JsonUtil.toJson(param),
        ContentType.APPLICATION_JSON);
    Response response = client.performRequest("POST", urlDelete,
        Collections.emptyMap(), entity);
    return getResponseEntityFromResponse(response);
}
 
源代码29 项目: Tenable.io-SDK-for-Java   文件: AsyncHttpService.java
/**
 * Makes an HTTP POST request using the given URI and optional body.
 *
 * @param uri the URI to use for the POST call
 * @param json Optional, can be null. the JSON to POST
 * @return the resulting HttpFuture instance
 */
public HttpFuture doPost( URI uri, JsonNode json ) {
    HttpPost httpPost = new HttpPost( uri );

    String body = null;
    if( json != null ) {
        body = jsonHelper.serialize( json );
        httpPost.setEntity( new NStringEntity( body, ContentType.create( "application/json", "UTF-8" ) ) );
    }

    return new HttpFuture( this, httpPost, asyncClient.execute( httpPost, null ), body );
}
 
源代码30 项目: Tenable.io-SDK-for-Java   文件: AsyncHttpService.java
/**
 * Makes an HTTP PUT request using the given URI and optional body.
 *
 * @param uri the URI to use for the PUT call
 * @param json Optional, can be null. the JSON to PUT
 * @return the resulting HttpFuture instance
 */
public HttpFuture doPut( URI uri, JsonNode json ) {
    HttpPut httpPut = new HttpPut( uri );

    String body = null;
    if( json != null ) {
        body = jsonHelper.serialize( json );
        httpPut.setEntity( new NStringEntity( body, ContentType.create( "application/json", "UTF-8" ) ) );
    }

    return new HttpFuture( this, httpPut, asyncClient.execute( httpPut, null ), body );
}
 
 类所在包
 类方法
 同包方法