Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.springframework.web.client.HttpClientErrorException: 401 Unauthorized

I have web service URL:

http://myservice.local/aprovalanduser/?format=json&Name=India

When I am calling this URL using

resttemplate httpsrestTemplate.getForObject(uri, userdetails[].class)

I am getting error:

org.springframework.web.client.HttpClientErrorException: 401 Unauthorized

in the web service method:

method: "GET", 
data: xmlData, 
contentType: "application/xml", 
dataType: "xml", 
async: true, 
crossDomain: false,

I am setting the header only for XML like below:

headers.setContentType(MediaType.APPLICATION_XML);
like image 603
Sharma Avatar asked Oct 13 '16 15:10

Sharma


2 Answers

Http status code 401 means that you need to supply credentials to access the service. The way you present the credentials dependends on the authentication mechanism used by the service

For example if it uses Basic Authentication then you need to add a Authorization request header with Basic prefix and a base64 encoded combination of username and password separated by :

like image 85
ekem chitsiga Avatar answered Sep 29 '22 09:09

ekem chitsiga


Here is the code which does basic authentication as suggested by @ekem chitsiga

String plainCreds = "username:password";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Basic " + base64Creds);
HttpEntity<String> request = new HttpEntity<String>(headers);

RestTemplate restTemplate = new RestTemplate();
String url = "http://myservice.local/aprovalanduser/?format=json&Name=India";
ResponseEntity<Object> response = restTemplate.exchange(url, HttpMethod.GET, request, Object.class);
response.getBody();
like image 42
Venom Avatar answered Sep 29 '22 09:09

Venom