In this post we’re going to
- send Http Request
- get Http Response
- get Http Response content as Java object
For sending requests and getting responses we will use Apache Http Client (org.apache.httpcomponents)
Apache Http Client Maven dependency
First of all we need to add a Maven dependency for Apache Http Client
Apache Http Client alows us to send Http requests and get Http responses.
Find other posts about GET, PUT and DELETE requests.
POST HTTP Request
This is how to create a simple POST HTTP request
Here url
is the url of the web service endpoint or the url of the web site page.
Let’s assume we have some user service and we want to create a new user the url would be https://www.user-service-example.com/api/users
.
We should send a request with the new user info in JSON format.
HTTP Request Headers
To do that we have to set headers for the request. Headers is the array that contains key-value pairs. In our case headers look like this
or like this
That means that the request payload is in JSON format and we expect a response to be also in JSON format.
Now we should set the payload.
Apache HttpClient
Now you have to create a HTTP client, send POST request, get a response and close.
HttpResponse. response.getEntity().getContent()
We access the Http response content with response.getEntity().getContent().
If you expect the response body (response.getEntity().getContent()) to be a JSON then you can convert that to a Java object.
Convert response.getEntity().getContent() from JSON to object
See more about How to convert JSON to Java Object.
Response Code
You also can verify the response code if you need.
Apache HttpClient - complete example
You may also find these posts interesting: