Java使用apache http将json文件发布到elasticsearch

Sah*_*viz 3 apache json http-post elasticsearch

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

文件的内容是

{"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
Run Code Online (Sandbox Code Playgroud)

最后换一行。

但是我无法使用 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);
}
Run Code Online (Sandbox Code Playgroud)

最终输出没有信息

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
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激

kee*_*ety 5

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

您可以使用 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);
}
Run Code Online (Sandbox Code Playgroud)