gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:12:11 25 4
gpt4 key购买 nike

我可以使用 curl -XPUT localhost:9200/_bulk --data-binary @other2.json

运行 curl 将文件上传到 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

任何帮助将不胜感激

最佳答案

MultipartEntityBuilder 将 mime header 字段添加到请求正文。这对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);
}

关于json - Java 使用 apache http 将 json 文件发布到 elasticsearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27191450/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com