Java Spring RestTemplate getForObject() 给出 401 未经授权的异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19752691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:55:53  来源:igfitidea点击:

Spring RestTemplate getForObject() giving 401 unauthorized exception

javaspringrestprestashopresttemplate

提问by lsc

In my browser follwing rest API url is working and I can see XML results.

在我的浏览器中,rest API url 正在工作,我可以看到 XML 结果。

"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.

我想从 Java 客户端调用这个 url 并获得结果。为此,我正在使用 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?

不知道为什么会这样。我们不能用 RestTemplate 以 username@host/appplication 的形式调用 URL 吗?还是我使用 RestTemplate 调用此 URL 的方式不正确?

regards, -Lasith.

问候,-Lasith。

回答by Amar

I faced similar problem and solved it using resttemplate.exchangemethod. 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:

我遇到了类似的问题并使用resttemplate.exchange方法解决了它。这些步骤将您的身份验证详细信息放在 RestRequestHeaderInfo 中,该信息应该在内部HttpEntity<MultiValueMap<String, String>>将此实体传递到如下所示的交换方法中:

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 Hymanson library in my classpath: It worked.

如果响应是 json 格式,就像在我的情况下一样,响应是相应数据的持有者类,这些数据将由我的类路径中的 Hymanson 库填充:它有效。