I am using elasticsearch Java API and trying to make a curl call in order to find out whether a document exists in my index or not. This is how it is done in the command line. As far as I can tell from the posts here, I should either use HttpURLConnection java class or apache httpclient to send the curl request in java. My request should be like :
curl -i -XHEAD http://localhost:9200/indexName/mappingName/docID
.
There are actually many questions on how to send curl requests via java, but the answers are not that explanatory - thus I am not sure how to configure the request parameters for the curl head request. So far, I have reproduced this answer from Ashay and it doesn't work.
Does anybody send curl calls in elasticsearch's java API and can explain how to do it?
Here is my code and the error I get is "java.net.MalformedURLException: no protocol"
import org.apache.commons.codec.binary.Base64;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
String encodedURL = URLEncoder.encode(new StringBuilder()
.append("http://").append(serverName).append(":9200/") // elasticsearch port
.append(indexName).append("/").append(mappingName).append("/")
.append(url).toString(), "UTF-8"); // docID is a url
System.out.print("encodedURL : " + encodedURL + "\n");
URL url = new URL(new StringBuilder().append(encodedURL).toString());
System.out.print("url "+ url.toString() + "\n");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("X-Requested-With", "Curl");
connection.setRequestMethod("HEAD");
String userpass = new StringBuilder().append(username).append(":").append(password).toString();
String basicAuth = new StringBuilder().append("Basic ").append(new String(new Base64().encode(userpass.getBytes()))).toString();
connection.setRequestProperty("Authorization", basicAuth);
String inputLine;
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
P.S. the document ids of this index are urls and that is why I need to encode them. On the other hand, I am not sure whether I should encode the full http request or not.