i am using spring boot to call a openfeign client and from the Response of that feign i need to extract some header values.how can i do that. can anybody help please. just help me wheather we can do that or not!
Asked
Active
Viewed 3,460 times
2 Answers
4
Yes, you can do that. With Feign, we usually declare our interface with the method returning our class and Feign will automatically de-serialise the response from JSON into our POJO.
Here is the interface (operation):
@FeignClient(name = "library-book-service")
@RequestMapping("books")
public interface BookClient {
@GetMapping
public List<Book> getBooks(
@RequestParam("page") Optional<Integer> pageNum,
@RequestParam("size") Optional<Integer> pageSize,
@RequestParam("reader") Optional<Long> readerId);
}
And then you can use the feign client like this:
@Service
@RequiredArgsConstructor
public class BookService {
private final @NonNull BookClient bookClient;
public List<Book> retrieveBooks(
Optional<Integer> pageNum,
Optional<Integer> pageSize,
Optional<Long> readerId) {
return bookClient.getBooks(pageNum, pageSize, readerId);
}
However, in order to have access to the response headers, you need to declare your methods to return feign.Response
.
import feign.Response;
@FeignClient(name = "library-book-service")
@RequestMapping("books")
public interface BookClient {
@GetMapping
public Response getBooks(
@RequestParam("page") Optional<Integer> pageNum,
@RequestParam("size") Optional<Integer> pageSize,
@RequestParam("reader") Optional<Long> readerId);
}
This way you can have access to the response body and headers:
@Service
@RequiredArgsConstructor
public class BookService {
private final @NonNull BookClient bookClient;
private final @NonNull ObjectMapper objectMapper;
public List<Book> retrieveBooks(
Optional<Integer> pageNum,
Optional<Integer> pageSize,
Optional<Long> readerId) {
var response = bookClient.getBooks(pageNum, pageSize, readerId);
if (response == null) {
return Collections.emptyList();
}
// retrieve body
var books = objectMapper.readValue(
new BufferedReader(new InputStreamReader(response.body().asInputStream(), StandardCharsets.UTF_8)),
new TypeReference<List<Book>>(){});
// retrieve headers
Map<String, Collection<String>> headers = response.headers();
// ... do whatever you need with the headers
return books;
}

dbaltor
- 2,737
- 3
- 24
- 36
2
You can use import feign.Response
as a response like:
@PostMapping("/test")
Response test(@RequestBody TestRequest testRequest);
then you can reach http header
response.headers().get(HEADER_NAME).toString();
if you want get body in this case you have to some json-string manipulation by use response.body()
this page may help you for this

tayfurunal
- 89
- 4