Spring RestTemplate getForObject() giving 401 unauthorized exception
I faced similar problem and solved it using resttemplate.exchange method. The steps are put your authentication details in RestRequestHeaderInfo which should be inside HttpEntity<MultiValueMap<String, String>>
pass this entity into the exchange method like below:
response = restTemplate.exchange(url, HttpMethod.GET, request, Response.class);
If response is in json format like in my case, Response is the holder class for the corresponding data which will be populated by Jackson library in my classpath: It worked.
lsc
Software Engineer having 6.5 years of experience in Software Development also worked with giant players in software world like Microsoft, IBM and BT (British Telecom). Specialties: Java language, C#, Web Services, WCF, Eclipse plug-ins, UML, EMF, ASP, Maven, Struts, Spring, Velocity, GIS
Updated on April 16, 2021Comments
-
lsc about 3 years
In my browser follwing rest API url is working and I can see XML results.
"http://V7846EKZZJ1OJAW486D66IS7GO24XKUZ@localhost:8090/prestashop/api/products/1"
I want to call this url from Java client and get results. For that I am using RestTemplate.
String result = restTemplate.getForObject("http://V7846EKZZJ1OJAW486D66IS7GO24XKUZ@localhost:8090/prestashop/api/products/1" , String.class);
this is giving following error,
WARNING: GET request for http://V7846EKZZJ1OJAW486D66IS7GO24XKUZ@localhost:8090/prestashop/api/products/1 resulted in 401 (Unauthorized); invoking error handler Disconnected from the target VM, address: '127.0.0.1:49533', transport: 'socket' org.springframework.web.client.HttpClientErrorException: 401 Unauthorized at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:88) at org.springframework.web.client.RestTemplate.handleResponseError(RestTemplate.java:537)
Not sure why this is happening. Can't we call URL in form username@host/appplication with RestTemplate? Or is it incorrect the way I am calling this URL with RestTemplate?
regards, -Lasith.