Larry Garfield
05/16/2024, 7:42 PMval body = objectMapper.writeValueAsString(error)
val request = HttpEntity<String>(body, headers)
restTemplate.exchange(uri, HttpMethod.POST, request)
I just want to send a postback message to an endpoint. I do not care about the response at all. However, RestTemplate.exchange() insists on a 4th argument that is the class name to cast the response into. Is there an alternate approach for when I don’t know or care what comes back, I just want to send-and-forget? (This is in SpringBoot, but I’m not sure if that matters. Still new to the ecosystem and not sure where the lines are.)Youssef Shoaib [MOD]
05/16/2024, 9:21 PMAny
(or Object
in Java) then it should always succeedLarry Garfield
05/16/2024, 10:16 PMrestTemplate.exchange(uri, <http://HttpMethod.POST|HttpMethod.POST>, request, Any::class.java)
That at least keeps my IDE happy. I feel like I’m probably not doing this optimally, but I guess it works?Youssef Shoaib [MOD]
05/16/2024, 10:41 PMfun RestTemplate.exchangeAndForget(uri: Uri, method: HttpMethod, request: HttpEntity) {
exchange(uri, method, request, Any::class.java)
}
Youssef Shoaib [MOD]
05/16/2024, 10:44 PMexchange
method using Kotlin's reified
types:
inline fun <reified T> RestTemplate.exchange(uri: Uri, method: HttpMethod, request: HttpEntity): T =
exchange(uri, method, request, T::class.java)
and then when you don't care about the result you can simply do restTemplate.exchange<Any?>(uri, <http://HttpMethod.POST|HttpMethod.POST>, request)
, and when you care about the result, then you can use the right typeRiccardo Lippolis
05/17/2024, 6:47 AMexchange
method that @Youssef Shoaib [MOD] mentioned above is available, see: https://github.com/spring-projects/spring-framework/blob/93387e69b53620b13b379bd972a18cdc3fd54be7/spring-web/src/main/kotlin/org/springframework/web/client/RestOperationsExtensions.kt#L275
Which means you could already write it as follows, as long as you (let IntelliJ) add the necessary import:
import org.springframework.web.client.exchange
// ...
restTemplate.exchange<Any?>(uri, HttpMethod.POST, request)
Larry Garfield
05/17/2024, 1:42 PM