为什么RestTemplate忽略rootUri?

5
我有以下Groovy代码:
def test(){
    RequestEntity request=RequestEntity.method(HttpMethod.GET,new URI("/some/resource"))
        .accept("text/plain")
        .build()

    def template=new RestTemplateBuilder()
        .rootUri("http://example.com/api")
        .build()
    def response=template.exchange(request,String)
    assert response.statusCode.value()==200
}

它返回类似于这样的东西:
org.springframework.web.client.ResourceAccessException: I/O error on GET request for "/some/resource": null; nested exception is org.apache.http.client.ClientProtocolException
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:666)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:628)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:590)
    …
Caused by: org.apache.http.client.ClientProtocolException
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:187)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
    at org.springframework.http.client.HttpComponentsClientHttpRequest.executeInternal(HttpComponentsClientHttpRequest.java:89)
    at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48)
    …
Caused by: org.apache.http.ProtocolException: Target host is not specified
    at org.apache.http.impl.conn.DefaultRoutePlanner.determineRoute(DefaultRoutePlanner.java:71)
    at org.apache.http.impl.client.InternalHttpClient.determineRoute(InternalHttpClient.java:125)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
... 15 more

看起来RestTemplateBuilder忽略了rootUri。有没有办法让所有以"/"开头的请求都添加"http://example.com/api"?


你能在构造请求对象之前进行检查吗? - ajc
@ajc 不错的想法。但在我的情况下,需要进行一些重构和/或其他创意变化。 - User1
1个回答

6

我有类似的问题。通过更改解决了它。

restTemplate.postForEntity(URI.create("/foo", request, SomeClass.class)

to

restTemplate.postForEntity("/foo", request, SomeClass.class)

基本上,尝试将路径指定为字符串而不是URI。之后它应该遵守rootUri。希望这可以帮助您。

行为在此处解释:https://github.com/spring-projects/spring-boot/issues/7891


3
参考问题谈到了TestRestTemplate。实际的RestTemplate行为没有改变:如果你传递一个字符串,会调用RootUri处理程序;如果你传递一个URI,则不会。 - Andreas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接