First of all we need to add a Maven dependency for Apache Http Client
Apache Http Client Maven dependency
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
We usually use PUT Http request to update data on the server for example a user. DELETE Http request is used to delete something for example a user.
PUT HTTP Request
HttpPut put = new HttpPut(url);
DELETE HTTP Request
HttpDelete delete = new HttpDelete(url);
Here url
is the url of the web service endpoint for example https://www.user-service-example.com/api/users/{id}
. {id}
is the unique userId
of the user that you want to update (PUT request) or delete (DELETE request).
PUT Http request should contain the info to update the existing user. DELETE Http request doesn’t have any payload.
All steps are similar to the steps that described in How to send POST HTTP request and get HTTP response in Java with Apache Http Client
Complete example for PUT HTTP Request
String url = "https://www.google.com/api/users/{id}"; // replace {id} with userId
HttpPut put = new HttpPut(url);
Header headers[] = {
new BasicHeader("Content-type", "application/json"),
new BasicHeader("Accept", "application/json")
};
put.setHeaders(headers);
String json = new Gson().toJson(new User("Jane", "Doe", "jane.doe@yahoogmail.com"));
put.setEntity(new StringEntity(json));
HttpClient client = HttpClients.custom().build();
HttpResponse response = client.execute(put);
String result = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8);
User updatedUser = gson.fromJson(result, User.class);
int responseCode = response.getStatusLine().getStatusCode();
String statusPhrase = response.getStatusLine().getReasonPhrase();
response.getEntity().getContent().close();
Complete example for DELETE HTTP Request
String url = "https://www.google.com/api/users/{id}"; // replace {id} with userId
HttpDelete delete = new HttpDelete(url);
Header headers[] = {
// define headers if needed new BasicHeader("key", "value");
};
delete.setHeaders(headers);
HttpClient client = HttpClients.custom().build();
HttpResponse response = client.execute(delete);
int responseCode = response.getStatusLine().getStatusCode();
String statusPhrase = response.getStatusLine().getReasonPhrase();
response.getEntity().getContent().close();
You may also find these posts interesting: