An HTTP client is one of the easiest clients to create. It's very handy because it allows for the calling, not only of the internal methods as the native protocol does, but also of third-party calls implemented in plugins that can be only called via HTTP.
You need an up-and-running Elasticsearch installation as we described in the Downloading and installing Elasticsearch recipe in Chapter 2, Downloading and Setup.
A Maven tool, or an IDE that natively supports it for Java programming such as Eclipse or IntelliJ IDEA, must be installed.
The code for this recipe is in the chapter_14/http_java_client
directory.
For creating a HTTP client, we will perform the following steps:
search.maven.org
. To enable the compilation in your Maven pom.xml
project just add the following code:<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
get
method the code will look like the following:import org.apache.http.*; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import java.io.*; public class App { private static String wsUrl = "http://127.0.0.1:9200"; public static void main(String[] args) { CloseableHttpClient client = HttpClients.custom() .setRetryHandler(new MyRequestRetryHandler()).build(); HttpGet method = new HttpGet(wsUrl+"/test-index/test- type/1"); // Execute the method. try { CloseableHttpResponse response = client.execute(method); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { System.err.println("Method failed: " + response.getStatusLine()); }else{ HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity); System.out.println(responseBody); } } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } } }
{"_index":"test-index","_type":"test- type","_id":"1","_version":1,"exists":true, "_source" : {...}}
We perform the previous steps to create and use an HTTP client:
CloseableHttpClient client = HttpClients.custom() .setRetryHandler(new MyRequestRetryHandler()).build();
HttpRequestRetryHandler
, which monitors the execution and repeats it three times before raising an error.HttpGet
and the URL will be item index/type/id
(similar to the CURL example in the Getting a document recipe in Chapter 4, Basic Operations). To initialize the method, the code is:HttpGet method = new HttpGet(wsUrl+"/test-index/test-type/1");
basicAuth
, but works very well for non-complex deployments:HttpHost targetHost = new HttpHost("localhost", 9200, "http"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials("username", "password")); // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); // Add AuthCache to the execution context HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider);
context
must be used in executing the call:response = client.execute(method, context);
gzip
data compression over HTTP to reduce bandwidth usage. To do that, we can add a custom header to the call informing the server that our client accepts encoding: Accept-Encoding
, gzip
:request.addHeader("Accept-Encoding", "gzip");
response = client.execute(method, context);
OK
, the return status should be 200
. In the previous code the check is done in the if
statement:if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
OK
and the status code of the response is 200
, we can read the answer:HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity);
The response is wrapped in HttpEntity
, which is a stream.
The HTTP client library provides a helper method EntityUtils.toString
that reads all the content of HttpEntity
as a string. Otherwise we'd need to create some code to read from the string and build the string.
Obviously, all the read parts of the call are wrapped in a try-catch
block to collect all possible errors due to networking errors.
3.133.150.41