3

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

"http://V7846EKZZJ1OJAW486D66IS7GO24XKUZ@localhost:8090/prestashop/api/products/1"

我想从 Java 客户端调用这个 url 并获得结果。为此,我正在使用 RestTemplate。

String result = restTemplate.getForObject("http://V7846EKZZJ1OJAW486D66IS7GO24XKUZ@localhost:8090/prestashop/api/products/1"
    , String.class);

这给出了以下错误,

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)

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

问候,-Lasith。

4

2 回答 2

3

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.

于 2014-11-04T13:04:58.557 回答
0

您还可以使用 restTemplete 拦截器添加令牌标头。这比交换方法更好,因为您不必每次都添加令牌。Lambda 表达式如下

RestTemplate restTemplate = new RestTemplateBuilder().interceptors((HttpRequest request, byte[] body, ClientHttpRequestExecution execution) -> {
  request.getHeaders().set(AUTHORIZATION, token);
  return execution.execute(request, body);}).build()
于 2021-04-15T22:26:07.727 回答