Created
March 8, 2021 11:23
-
-
Save silentsudo/255581d2bc74e533be76d29e0bf834c3 to your computer and use it in GitHub Desktop.
kotlin-sample-post-and-rest-template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.examlples.spring.kotlin.kotlinspringsamples | |
import org.springframework.boot.web.client.RestTemplateBuilder | |
import org.springframework.context.annotation.Bean | |
import org.springframework.context.annotation.Configuration | |
import org.springframework.web.client.RestTemplate | |
@Configuration | |
class AppConfig { | |
@Bean | |
fun restTemplate(): RestTemplate { | |
return RestTemplateBuilder().build() | |
} | |
} | |
package com.examlples.spring.kotlin.kotlinspringsamples | |
import org.springframework.boot.autoconfigure.SpringBootApplication | |
import org.springframework.boot.runApplication | |
@SpringBootApplication | |
class KotlinSpringSamplesApplication | |
fun main(args: Array<String>) { | |
runApplication<KotlinSpringSamplesApplication>(*args) | |
} | |
package com.examlples.spring.kotlin.kotlinspringsamples.controllers | |
import com.fasterxml.jackson.databind.ObjectMapper | |
import org.springframework.web.bind.annotation.* | |
import org.springframework.web.client.RestTemplate | |
import java.util.* | |
@RestController | |
@RequestMapping(value = ["sample"]) | |
class SampleController(val mapper: ObjectMapper, | |
val restTemplate: RestTemplate, | |
val requestLogs: MutableList<Request> = mutableListOf()) { | |
@GetMapping(value = ["/log"]) | |
fun logs(): List<Request> { | |
return Collections.unmodifiableList(requestLogs) | |
} | |
@PostMapping(value = ["/log"]) | |
fun log(@RequestBody request: Request): String { | |
requestLogs.add(request) | |
return "Added new request log, current count is ${requestLogs.size}" | |
} | |
@PostMapping(value = ["/log-rest-template"]) | |
fun logRestTemplate(@RequestBody request: Request): String { | |
val postForObject = restTemplate.postForObject("http://localhost:8080/sample/log", request, String::class.java) | |
return postForObject.plus(" via, rest template") | |
} | |
} | |
data class Request(val customer: Customer, val dealer: Dealer) | |
data class Customer(val id: String, val name: String) | |
data class Dealer(val id: String, val name: String) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment