Effettuare richieste HTTP in Spring Boot e Kotlin

Mattepuffo's logo
Effettuare richieste HTTP in Spring Boot e Kotlin

Effettuare richieste HTTP in Spring Boot e Kotlin

Come abbiamo detto più volte, Spring Boot è un framework molto flessibile, che ci consente di fare parecchie operazioni di vario genere.

In questo articolo vediamo come effettuare una richiesta HTTP con RestTemplate e Kotlin.

L'unica dipendenza è questa:

implementation("org.springframework.boot:spring-boot-starter-web")

Potreste già averla in base a come avete creato il progetto.

Poi creiamo una data class che rappresenta il record JSON che ci arriva:

package com.spring.kotlin

data class Post(
  val userId: Int,
  val id: Int,
  val title: String,
  val body: String
)

Infine il nostro controller:

package com.spring.kotlin

import org.springframework.core.ParameterizedTypeReference
import org.springframework.http.HttpMethod
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.client.RestTemplate

@RestController
class RootController {

  private val restTemplate = RestTemplate()

  @GetMapping("/")
  fun root(): List<Post>? {
    val url = "https://jsonplaceholder.typicode.com/posts"

    val response = restTemplate.exchange(
      url,
      HttpMethod.GET,
      null,
      object : ParameterizedTypeReference<List<Post>>() {}
    )

    return response.body
  }
}

Enjoy!


Condividi

Commentami!