Reputation: 1263
using postman, for a GET request with header values for user name and password and successfully hitting a rest service and getting response 200.
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;
}
Upvotes: 1
Views: 2334
Reputation: 727
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;
}
Upvotes: 1