【问题标题】:Java post json file to elasticsearch with apache httpJava 使用 apache http 将 json 文件发布到 elasticsearch
【发布时间】:2014-11-28 15:08:16
【问题描述】:

我可以运行 curl 以使用 curl -XPUT localhost:9200/_bulk --data-binary @other2.json 将文件上传到 elasticsearch

文件的内容是

{"index":{"_index":"movies","_type":"movie","_id":1}}\n
{"title": "Movie1","director": "director1","year":1962}\n
{"index":{"_index":"movies","_type":"movie","_id":2}}\n
{"title": "Movie2","director": "director2","year": 1972}\n
{"index":{"_index":"movies","_type":"movie","_id":3}}\n
{"title": "Movie3","director": "director3","year": 1972}\n

最后换行。

但是我无法使用 apache http 客户端发布相同的文件

public static void main(String[] args) throws Exception {
    JsonResponse http = new JsonResponse();

    System.out.println("\nTesting 2 - Send Http POST request");
    http.sendFile();
}
private void sendFile() throws Exception{
    String fileName = "C:\\other2.json";
    File jsonFile = new File(fileName);


    HttpEntity  entity = MultipartEntityBuilder.create()
        .addBinaryBody("file", jsonFile,org.apache.http.entity.ContentType.APPLICATION_JSON, jsonFile.getName())
        .build();

    HttpPost post = new HttpPost("http://localhost:9200/_bulk");
    post.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    HttpClient client = clientBuilder.build();

    post.addHeader("content-type", "application/json");
    post.addHeader("Accept","application/json");

    HttpResponse response = client.execute(post);

    System.out.println("Response: " + response);
}

最终的输出是无信息的

Testing 2 - Send Http POST request
Response: HTTP/1.1 400 Bad Request [Content-Type: application/json; 
charset=UTF-8, Content-Length: 152] org.apache.http.impl.execchain.ResponseEntityWrapper@124bec88

任何帮助将不胜感激

【问题讨论】:

    标签: json apache elasticsearch http-post


    【解决方案1】:

    MultipartEntityBuilder 将 mime 标头字段添加到请求正文。这对 bulk api 无效。 此外,多部分请求正文中还有其他元信息,例如请求正文中的boundary,这将导致错误请求

    您可以使用 FileEntity 来实现与代码片段相同的内容:

    private void sendFile() throws Exception{
        String fileName = "C://others2.json";
        File jsonFile = new File(fileName);
    
        HttpEntity  entity = new FileEntity(jsonFile);
    
        HttpPost post = new HttpPost("http://localhost:9200/_bulk");
        post.setEntity(entity);
    
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        HttpClient client = clientBuilder.build();
    
        post.addHeader("content-type", "text/plain");
        post.addHeader("Accept","text/plain");
    
        HttpResponse response = client.execute(post);
    
        System.out.println("Response: " + response);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 2014-06-05
      • 2017-11-11
      • 2015-02-24
      • 1970-01-01
      相关资源
      最近更新 更多