Reputation: 1892
I have created a Feign client StorageClient like as shown below:
@Headers(HttpHeaders.ACCEPT + ": " + MediaType.APPLICATION_JSON_UTF8_VALUE)
interface StorageApi {
@RequestLine("GET /api/v1/files/{fileId}")
fun getFileMeta(@Param("fileId") fileId: Long): Response
}
@Service
class StorageClient(private val storageApi: StorageApi) {
fun getFile(fileId: Long): StorageFile = storageApi.getFileMeta(fileId)
}
In addition to the StorageClient client, the getFileMeta()
method (interface StorageApi
) is also used to check for the the status (method isFileExists()
):
fun isFileExists(fileId: Long): Boolean = storageApi.getFileMeta(fileId).status() != 404
For this reason, I cannot write explicitly:
@RequestLine("GET /api/v1/files/{fileId}")
fun getFileMeta(@Param("fileId") fileId: Long): StorageFile
How can I decode the Response body so that it is possible to return an object of type StorageFile
from the getFile()
(class StorageClient
) method? Or maybe there is some way to work with both the status
of the received Response
and its body
?
Upvotes: 0
Views: 8764
Reputation: 1767
This answer is a little late, you can decode the body manually using a JSON deserializer such as Jackson:
import com.fasterxml.jackson.databind.ObjectMapper
import org.apache.commons.io.IOUtils
val json = IOUtils.toString(response.body().asInputStream(), Charsets.UTF_8)
val storageFile = ObjectMapper().readValue(json, StorageFile::class.java)
Make sure to add Jackson as dependency. For example in your pom.xml if you're using maven:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>..</version>
</dependency>
An in-depth tutorial on Jackson is available here: https://www.baeldung.com/jackson-object-mapper-tutorial.
Important notice: Make sure to call response.close()
when you're done. Otherwise this will lead to a resource leak.
Upvotes: 2