Search code examples
postmanresttemplatehttp-status-code-401unauthorized

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


using postman, for a GET request with header values for user name and password and successfully hitting a rest service and getting response 200.

enter image description here

But when trying to access same request by java code using spring RestTemplate getting 401-unauthorized issue.

this is the code

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

Solution

  • I haven't tested it, but try something like this:

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