Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is RestTemplate ignoring rootUri

I have the following Groovy code:

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
}

It returns something like this:

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

It looks like the rootUri is being ignored by the RestTemplateBuilder. Is there a way to make all requests starting with a "/" add the "http://example.com/api"?

like image 214
User1 Avatar asked Nov 10 '17 20:11

User1


1 Answers

Had similar problem. Solved it by changing

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

to

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

So basically, try to specify path as String and not as URI. After that it should respect rootUri. Hope this helps.

Behaviour explained here: https://github.com/spring-projects/spring-boot/issues/7891

like image 85
user3029106 Avatar answered Sep 16 '22 23:09

user3029106