I am requesting an interface with feign and need to get the Headers
value for that interface.
I have used feign for the requested interface headers transfer parameters before, pass token to headers:
@RequestMapping(method = RequestMethod.GET, value = "/api/get-store-list")
List<Store> getStoreList(@RequestHeader("Authorization") String Authorization);
However, this interface puts the amount of data in the x-total-count
of headers, so I still need to get the value of x-total-count
.
How do I get the value of x-total-count
.
Feign has the headers in the Response
object, and that can be the return value:
public interface Swapi {
@RequestLine("GET /people/{id}/")
Response personResponse(@Param("id") int person);
}
Now you can call headers()
on the result. That, of course, leaves you with the body as a string, which is not pretty. Let’s try something more Feign like.
@Data
public class Person {
String name;
int height;
int mass;
}
public interface Swapi {
@RequestLine("GET /people/{id}/")
Person person(@Param("id") int person);
}
Now the headers are hidden again, but they are still available to the decoder, which is the place that I will plug in:
@RequiredArgsConstructor
public class HeaderReadingDecoder implements Decoder {
private final Decoder wrappedDecoder;
@Override
public Object decode(Response response, Type type) throws IOException {
var server = response.headers().getOrDefault("server",
List.of("")).iterator().next();
System.out.println("server = " + server);
var etag = response.headers().getOrDefault("etag",
List.of("")).iterator().next();
System.out.println("etag = " + etag);
return wrappedDecoder.decode(response, type);
}
}
Of course, System.out
is evil, but I really don’t know yet what you want to do with that header value. It’s up to you. Now you can use this with:
Swapi swapi = Feign.builder()
.decoder(new HeaderReadingDecoder(new JacksonDecoder()))
.target(Swapi.class, "https://swapi.co/api");
Person person = swapi.person(2);
System.out.println("person = " + person);
And you will get:
server = cloudflare
etag = "3a58f420395ff0deed943e331d3bf74b"
person = Person(name=C-3PO, height=167, mass=75)