Spring header 中的 RestTemplate credential/Authorization 获得 401-unauthorized,在邮递员中它工作正常

Spring RestTemplate credential/Authorization in header getting 401-unauthorized, where in postman it is working fine

使用邮递员,针对用户名和密码的 header 值的 GET 请求 并成功点击休息服务并获得响应 200。

但是当尝试使用 spring java 代码访问同一请求时 RestTemplate 出现 401-unauthorized 问题。

这是代码

      final String uri = "http://<host>:<port>/services/arecord";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", "admin");
        String password = "admin";

        map.add("password", password);
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

        RestTemplate restTemplate = new RestTemplate();

        try {
            ResponseEntity<String> response = restTemplate.exchange(uri, HttpMethod.GET,
                    new HttpEntity(createHeaders("admin", "admin")), String.class);
            String body = response.getBody();

        } catch (HttpClientErrorException e) {

            logger.info("****** ERROR *********** " + e.getMostSpecificCause());
            return true;
        }

我还没有测试过,但试试这样:

final String uri = "http://<host>:<port>/services/arecord";

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("username", "admin");
headers.set("password", "admin");

HttpEntity entity = new HttpEntity(headers);
RestTemplate restTemplate = new RestTemplate();

try {
      ResponseEntity<String> response = restTemplate.exchange(
        uri, HttpMethod.GET, entity, String.class);

      String body = response.getBody();

} catch (HttpClientErrorException e) {
      logger.info("****** ERROR *********** " + e.getMostSpecificCause());
      return true;
}