Spring Boot OkHttp Tutorial

Introduction

OkHttp is a popular HTTP client library for Java that is known for its efficiency and ease of use. It supports HTTP/2 and WebSocket and allows for efficient HTTP calls with features such as connection pooling and transparent GZIP compression. This tutorial will demonstrate how to integrate OkHttp into a Spring Boot application and perform CRUD operations.

To learn more about OkHttp, check out this guide: OkHttp.

Prerequisites

  1. Java Development Kit (JDK) 17 or later
  2. Apache Maven installed
  3. An IDE like IntelliJ IDEA or Eclipse

Step 1: Create a Spring Boot Project

You can create a Spring Boot project using Spring Initializr or your IDE.

Using Spring Initializr

  1. Go to Spring Initializr.
  2. Select the following options:
    • Project: Maven Project
    • Language: Java
    • Spring Boot: 3.0.0 or later
    • Group: com.example
    • Artifact: okhttp-demo
    • Name: okhttp-demo
    • Package name: com.example.okhttpdemo
    • Packaging: Jar
    • Java: 17 or later
  3. Add the following dependencies:
    • Spring Web
    • Spring Boot Starter Test
  4. Click "Generate" to download the project zip file.
  5. Extract the zip file and open the project in your IDE.

Step 2: Add OkHttp Dependency

Add the following dependencies to your pom.xml file:

<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <!-- Spring Boot Starter Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

    <!-- OkHttp -->
    <dependency>
        <groupId>com.squareup.okhttp3</groupId>
        <artifactId>okhttp</artifactId>
        <version>4.9.3</version>
    </dependency>
</dependencies>

Step 3: Create a Service to Use OkHttp

Create a new Java class named HttpService in the com.example.okhttpdemo package:

package com.example.okhttpdemo;

import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class HttpService {

    private final OkHttpClient client = new OkHttpClient();

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

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    public String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

    public String put(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(json, MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder()
                .url(url)
                .put(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }

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

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body().string();
        }
    }
}

Explanation:

  • OkHttpClient client = new OkHttpClient();: Initializes the OkHttp client.
  • Methods (get, post, put, delete): Define methods for performing GET, POST, PUT, and DELETE requests. Each method builds the request, executes it, and returns the response as a string.

Step 4: Create a Controller to Use the Service

Create a new Java class named HttpController in the com.example.okhttpdemo package:

package com.example.okhttpdemo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

@RestController
@RequestMapping("/http")
public class HttpController {

    private final HttpService httpService;

    @Autowired
    public HttpController(HttpService httpService) {
        this.httpService = httpService;
    }

    @GetMapping("/get")
    public String get(@RequestParam String url) throws IOException {
        return httpService.get(url);
    }

    @PostMapping("/post")
    public String post(@RequestParam String url, @RequestBody String json) throws IOException {
        return httpService.post(url, json);
    }

    @PutMapping("/put")
    public String put(@RequestParam String url, @RequestBody String json) throws IOException {
        return httpService.put(url, json);
    }

    @DeleteMapping("/delete")
    public String delete(@RequestParam String url) throws IOException {
        return httpService.delete(url);
    }
}

Explanation:

  • HttpController uses HttpService to perform HTTP operations.
  • Each endpoint (/get, /post, /put, /delete) calls the corresponding method in HttpService.

Step 5: Create the Main Application Class

Create a main application class named OkhttpDemoApplication in the com.example.okhttpdemo package:

package com.example.okhttpdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class OkhttpDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(OkhttpDemoApplication.class, args);
    }
}

Explanation: The OkhttpDemoApplication class contains the main method, which is the entry point of the Spring Boot application. The @SpringBootApplication annotation is a convenience annotation that adds all the following:

  • @Configuration: Tags the class as a source of bean definitions for the application context.
  • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings.
  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the specified package.

Step 6: Test the Application

Start your Spring Boot application and use tools like Postman or curl to test the HTTP operations.

Test GET Request

  • Method: GET
  • URL: http://localhost:8080/http/get?url=https://jsonplaceholder.typicode.com/posts/1

Test POST Request

  • Method: POST
  • URL: http://localhost:8080/http/post?url=https://jsonplaceholder.typicode.com/posts
  • Body:
    {
        "title": "foo",
        "body": "bar",
        "userId": 1
    }
    

Test PUT Request

  • Method: PUT
  • URL: http://localhost:8080/http/put?url=https://jsonplaceholder.typicode.com/posts/1
  • Body:
    {
        "id": 1,
        "title": "foo",
        "body": "bar",
        "userId": 1
    }
    

Test DELETE Request

  • Method: DELETE
  • URL: http://localhost:8080/http/delete?url=https://jsonplaceholder.typicode.com/posts/1

Conclusion

In this tutorial, we demonstrated how to integrate OkHttp into a Spring Boot application and perform various HTTP operations. We covered the creation of a service to handle HTTP requests, a controller to expose endpoints, and provided examples of GET, POST, PUT, and DELETE requests. 

By following these steps, you can efficiently use OkHttp to handle HTTP operations in your Spring Boot applications.

Comments