Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring RestTemplate getForObject() giving 401 unauthorized exception

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.

like image 755
lsc Avatar asked Jun 10 '26 02:06

lsc


1 Answers

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.

like image 144
Amar Avatar answered Jun 11 '26 16:06

Amar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!