【问题标题】:Spring RestTemplate credential/Authorization in header getting 401-unauthorized, where in postman it is working fine标头中的 Spring RestTemplate 凭据/授权得到 401 未经授权,在邮递员中它工作正常
【发布时间】:2019-01-17 14:20:10
【问题描述】:

使用邮递员,用于带有用户名和密码标头值的 GET 请求 并成功点击休息服务并获得响应 200。

但是当尝试通过 java 代码使用 spring 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;
        }

【问题讨论】:

    标签: postman resttemplate http-status-code-401 unauthorized


    【解决方案1】:

    我没有测试过,但是试试这样的:

    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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-24
      • 2021-03-19
      • 2018-07-01
      • 1970-01-01
      • 2016-02-10
      • 1970-01-01
      • 2019-11-09
      • 2012-04-04
      相关资源
      最近更新 更多