Vic*_*que 4 java spring spring-boot
我尝试构建一个 SpringFeign Client来封装对内部 API 的调用。在此请求中,我需要登录才能获取令牌,然后将其用作新请求的标头参数。为了动态设置令牌,我使用了下面的代码。
@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);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,除了登录正确并获取令牌之外,我的请求总是返回403 code. (我使用邮递员来检查请求是否应成功返回)。
唯一有效的解决方案是使用restTemplate下面的代码。
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);
Run Code Online (Sandbox Code Playgroud)
使用Spring引导2。
小智 5
您不能在@Header注释中使用动态值。但是,您可以@RequestHeader在输入参数中使用注释来执行此操作。
@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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13448 次 |
| 最近记录: |