我有以下的Groovy代碼:爲什麼RestTemplate忽略rootUri
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
它看起來像rootUri正在被RestTemplateBuilder忽略。有沒有辦法讓以「/」開頭的所有請求添加「http://example.com/api」?
是否有可能爲你做出檢查,建立請求對象之前? – ajc
@ajc好主意。沒有我的情況下沒有一些重構和/或其他創意的變化。 – User1