4

I tried to build a Spring Feign Client to encapsulate the call to an internal API. In this request, I need to make a login in order to get a token and then use it as a Header parameter for my new request. To set the token dynamically, I used the code below.

@FeignClient(value = "APIBuscarCep", url = "${url}")
public interface BuscarCepFeignClient {

    @RequestMapping(method = RequestMethod.GET, value = "url-complement", produces = "application/json")
    @Headers({"Authorization: {token}"})
    CepResponseDTO getAddressByCep(@Param("token") String token, @NotNull @PathVariable("cep") String cep);
}

Unfortunately, besides the login goes right and get token, my request always returns the 403 code. (I used postman to check if the request should return successfully).

The only solution that works was using restTemplate like the code below.

HttpHeaders headers = new HttpHeaders();

headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Authorization", token);
ResponseEntity<CepResponseDTO> exchange;

exchange = restTemplate.exchange(String.format("%s%s", endpoint, cep),              
                                 HttpMethod.GET, header, CepResponseDTO.class);

Question

  • Is there any difference between the building of those classes?
  • How can I make the request using Feign Client?

Specs

Using Spring boot 2.

Victor Henrique
  • 327
  • 1
  • 5
  • 16

1 Answers1

5

You can't use dynamic value in @Header annotation. However, you can use @RequestHeader annotation in the input param to do this.

@FeignClient(value = "APIBuscarCep", url = "${url}")
public interface BuscarCepFeignClient {

    @RequestMapping(method = RequestMethod.GET, value = "url-complement", produces = "application/json")
    CepResponseDTO getAddressByCep(@RequestHeader("Authorization") String token, @NotNull @PathVariable("cep") String cep);
}
Xavier FRANCOIS
  • 652
  • 4
  • 15
  • 1
    Can you attach the Feign debug logs ? You will see the full HTTP trace (headers, body, url), and it will be easy to debug as it works from Postman. See here https://stackoverflow.com/questions/42751269/feign-logging-not-working to activate logs – Xavier FRANCOIS Dec 06 '19 at 18:05
  • I also suggest setting up the log level for Trace to debug Feign Classes. – Victor Henrique Mar 11 '20 at 13:48