代码之家  ›  专栏  ›  技术社区  ›  AabinGunz

如何在java中使用ElasticsearchRestapi?

  •  4
  • AabinGunz  · 技术社区  · 12 年前

    我使用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)
    

    这是弹性搜索感觉截图

    enter image description here

    2 回复  |  直到 12 年前
        1
  •  7
  •   Raja    12 年前

    状态代码200代表“OK”
    check w3c ref


    你应该使用

        if(response.getStatusLine().getStatusCode() != 200){
            // Throw exception or something else
        } 
    
        2
  •  0
  •   Rohit Luthra    9 年前

    稍加修改后,代码就会运行。像 默认HttpClient 现在已折旧,您需要使用 HTTP客户端 无需更改状态代码,因为我验证了它在post请求中返回响应代码201,在get请求中返回200。如果您了解fiddler,我还附上了fiddler的会话截图。如果你不知道小提琴,你可以去 http://www.telerik.com/fiddler

    enter image description here

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