Java 为什么restemplate会忽略rootUri

Java 为什么restemplate会忽略rootUri,java,rest,groovy,resttemplate,Java,Rest,Groovy,Resttemplate,我有以下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")

我有以下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。有没有办法让所有以“/”开头的请求添加“”?

也有类似的问题。通过改变来解决它

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

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


此处解释的行为:

您是否可以在构建请求对象之前进行检查?@ajc好主意。在我的例子中,如果没有一些重构和/或其他创造性的更改,就不会出现这种情况。引用的问题是关于
testrestemplate
。实际的
restemplate
行为保持不变:如果传递字符串,则调用RootUri处理程序;如果传递URI,则不是。
restTemplate.postForEntity("/foo", request, SomeClass.class)