OkHttp DELETE Request Java Example

In this post, we will create an OkHttp DELETE HTTP request example in Java.
OkHTTP is an open source project designed to be an efficient HTTP client for Android and Java applications.
OkHttp supports Android 5.0+ (API level 21+) and Java 1.8+. In this article, we will write a code using Java 1.8+.

Maven Dependency

Let’s first add the library as a dependency into the pom.xml:
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.9.0</version>
</dependency>
To see the latest dependency of this library check out the page on Maven Central.
In this post, we will create a DELETE HTTP client for spring boot CRUD example project. This spring boot crud example project is deployed and up and running. Refer to this article - https://www.javaguides.net/2018/09/spring-boot-2-hibernate-5-mysql-crud-rest-api-tutorial.html.

OkHttp DELETE Request Java Example

In below example, we are deleting User with id = 1. Note that we are using delete() API:
package com.javaguides.okhttp.tutorial.crud;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpDelete {

    OkHttpClient client = new OkHttpClient();

    public String run(String url) throws IOException {
        Request request = new Request.Builder().url(url).delete().build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static void main(String[] args) throws IOException {
        OkHttpDelete example = new OkHttpDelete();
        String response = example.run("http://localhost:8080/api/v1/employees/1");
        System.out.println(response);
    }
}
Below diagram shows the screenshot of source code as well as output: 

Comments