How do I send an Http Post request?

The following code snippet will show you how to send an Http Post request using the Apache HttpComponents. We will send a post request to http://localhost:8080/register. We will include some parameters to the request using the NameValuePair object.

To pass this parameters to the Http Post request we create an instance of UrlEncodedFormEntity and pass the list of NameValuePair as the arguments. And before executing the request we set this entity object to the HttpPost.setEntity() method.

Let’s see the code below:

How do I execute Http Get request?

Below is an example using HttpClient library to retrieve the content of a website using Http Get request. We start by creating an instance of DefaultHttpClient class. We then define an Http get request by create an instance of HttpGet class and specify the Url of a website we are going to retrieve.

To execute the request we call the HttpClient.execute() method and pass the HttpGet as the arguments. This execution return an HttpResponse object. From this response object we can read the content of the website by accessing the getEntity().getContent() which will give us an InputStream to the content.

For more detail let’s see the code snippet below:

How do I get entity ContentType in HttpClient?

This code snippet show you how to get the content type of a result of executing an Http Get request. The ContentType can be obtained by using ContentType.getOrDefault() method and passing an HttpEntity as the arguments. The HttpEntity can be obtained from the HttpResponse object.

From the ContentType object we can get the mime-type by calling the getMimeType() method. This method will return a string value. To get the charset we can call the getCharset() method which will return a java.nio.charset.Charset object.

The output of our code snippet are: