Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中使用ElasticSearchRESTAPI?_Java_<img Src="//i.stack.imgur.com/RUiNP.png" Height="16" Width="18" Alt="" Class="sponsor Tag Img">elasticsearch_Httpclient_Apache Httpclient 4.x_Apache Commons Httpclient - Fatal编程技术网 elasticsearch,httpclient,apache-httpclient-4.x,apache-commons-httpclient,Java,elasticsearch,Httpclient,Apache Httpclient 4.x,Apache Commons Httpclient" /> elasticsearch,httpclient,apache-httpclient-4.x,apache-commons-httpclient,Java,elasticsearch,Httpclient,Apache Httpclient 4.x,Apache Commons Httpclient" />

如何在java中使用ElasticSearchRESTAPI?

如何在java中使用ElasticSearchRESTAPI?,java,elasticsearch,httpclient,apache-httpclient-4.x,apache-commons-httpclient,Java,elasticsearch,Httpclient,Apache Httpclient 4.x,Apache Commons Httpclient,我使用ApacheHTTP客户端来使用ElasticSearchRESTAPI,但我总是得到Http错误代码为200。请帮忙 Java代码 import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.util.Scanner;

我使用ApacheHTTP客户端来使用ElasticSearchRESTAPI,但我总是得到Http错误代码为200。请帮忙

Java代码

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.util.Scanner;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class ApacheHttpClientPost {

    public static void main(String[] args) {
        String path="C:\\Tools\\ElasticSearchApi\\javadoc.txt", filecontent="";
        ApacheHttpClientPost apacheHttpClientPost = new ApacheHttpClientPost();
        try {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost("http://localhost:9200/versioneg/message/_percolate");
            filecontent=apacheHttpClientPost.readFileContent(path);
            System.out.println(filecontent);
            StringEntity input = new StringEntity(filecontent);
            input.setContentType("application/json");
            postRequest.setEntity(input);
            HttpResponse response = httpClient.execute(postRequest);
            if (response.getStatusLine().getStatusCode() != 201) {
                throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
            }
            BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
            String output;
            System.out.println("Output from Server .... \n");
            while ((output = br.readLine()) != null) {

                System.out.println(output);
            }
            httpClient.getConnectionManager().shutdown();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String readFileContent(String pathname) throws IOException {

        File file = new File(pathname);
        StringBuilder fileContents = new StringBuilder((int)file.length());
        Scanner scanner = new Scanner(file);
        String lineSeparator = System.getProperty("line.separator");

        try {
            while(scanner.hasNextLine()) {        
                fileContents.append(scanner.nextLine() + lineSeparator);
            }
            return fileContents.toString();
        } finally {
            scanner.close();
        }
    }
}
控制台

{
   "doc": {
      "os": "Linux",
      "product": {
         "name": "abc",
         "version": 10.1,
         "configversion": 1,
         "arch": 32,
         "license": "commercial",
         "db": {
            "@type": "Oracle"
         }
      }
   }
}

Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 200
    at com.informatica.zanshin.esapi.utils.ApacheHttpClientPost.main(ApacheHttpClientPost.java:31)
这是elasticsearch sense屏幕截图


状态代码200代表“正常”


你应该使用

    if(response.getStatusLine().getStatusCode() != 200){
        // Throw exception or something else
    } 

稍加修改后,代码将运行。由于DefaultHttpClient现在已折旧,您需要使用HttpClient,并且无需更改状态代码,因为我验证了它在post请求中返回响应代码201,在get请求中返回200。如果您了解fiddler,我还附上了fiddler的会话屏幕截图。如果你不了解fiddler,你可以访问


出于好奇,为什么选择状态代码201作为要检查的值?
try {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost postRequest = new HttpPost("http://localhost:9200/versioneg/message/");

    StringEntity requestEntity = new StringEntity(resultJsonObject.toString(), ContentType.APPLICATION_JSON);
    System.out.println("resultJsonobject:  "+ resultJsonObject.toString());

    postRequest.setEntity(requestEntity);
    HttpResponse response = httpClient.execute(postRequest);
    if (response.getStatusLine().getStatusCode() != 201) {
        throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
    }
    BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
    String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);
    }
} catch (Exception e) {
    e.printStackTrace();
}