【问题标题】:How to use Elasticsearch Rest api in java?如何在 Java 中使用 Elasticsearch Rest api?
【发布时间】:2014-08-04 11:34:10
【问题描述】:

我正在使用 Apache Http 客户端来使用 ElasticSearch Rest Api,但我总是收到 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的感觉截图

【问题讨论】:

  • 出于好奇,您为什么选择状态码 201 作为要检查的值?

标签: java elasticsearch httpclient apache-httpclient-4.x apache-commons-httpclient


【解决方案1】:

状态码 200 代表“正常”
check w3c ref


你应该使用

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

【讨论】:

    【解决方案2】:

    稍加修改后,您的代码将运行。由于 DefaultHttpClient 现在已弃用,您需要使用 HttpClient 并且无需更改状态代码,因为我验证它在发布请求中返回响应代码 201 并在获取请求它返回 200。如果您了解提琴手,我还附上了提琴手的会话截图。如果您不了解 fiddler,可以访问http://www.telerik.com/fiddler

    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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-27
      • 2012-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      相关资源
      最近更新 更多