Java RestTemplate和外国客户机之间有什么区别?

Java RestTemplate和外国客户机之间有什么区别?,java,spring,spring-boot,Java,Spring,Spring Boot,我试图构建一个Spring假客户机,以封装对内部API的调用。在这个请求中,我需要登录以获取令牌,然后将其用作新请求的头参数。为了动态设置令牌,我使用了下面的代码 @FeignClient(value = "APIBuscarCep", url = "${url}") public interface BuscarCepFeignClient { @RequestMapping(method = RequestMethod.GET, value = "url-complement",

我试图构建一个Spring
假客户机
,以封装对内部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);
}
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);
不幸的是,除了登录正确并获取令牌之外,我的请求总是返回
403代码
。(我用邮递员检查请求是否应该成功返回)

唯一有效的解决方案是像下面的代码一样使用
restemplate

@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);
}
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);
HttpHeaders=newhttpheaders();
headers.setContentType(MediaType.APPLICATION_JSON);
添加(“授权”,令牌);
责任交换;
exchange=restTemplate.exchange(String.format(“%s%s”,端点,cep),
HttpMethod.GET、header、CepResponseDTO.class);
问题:
  • 这些课程的建设有什么不同吗
  • 我如何使用假客户端发出请求
规格
使用Spring boot 2。

您不能在
@标题
注释中使用动态值。但是,您可以在输入参数中使用
@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);
}

你能附加假调试日志吗?您将看到完整的HTTP跟踪(标题、正文、url),并且它将很容易从Postman进行调试。请参见此处以激活日志。我还建议为跟踪设置日志级别以调试外部类。