4

I am using Apache Http client for making use of ElasticSearch Rest Api, but I am always getting HTTP error code as 200. Please help

Java code

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

Console

{
   "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)

Here is elasticsearch sense screenshot

enter image description here

1
  • 1
    Out of curiosity, why did you pick status code 201 as the value to check against? Commented Dec 24, 2015 at 9:25

2 Answers 2

7

Status Code 200 stands for 'OK'
check w3c ref


You should use

    if(response.getStatusLine().getStatusCode() != 200){
        // Throw exception or something else
    } 
Sign up to request clarification or add additional context in comments.

Comments

0

After little modification your code will run. As DefaultHttpClient is now depreciated, you need to use HttpClient and there is no need to change status code because I verified it that in post request it returns response code 201 and in get request it returns 200.If you know about fiddler, I have also attached the fiddler's session screenshot. If you don't know about fiddler you can visit 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();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.