Spring-boot: TestRestTemplate does not resolve relative links with java.net.URI parameter

Created on 5 Jan 2017  路  5Comments  路  Source: spring-projects/spring-boot

According to the documentation, when using @SpringBootTest(webEnvironment=WebEnvironment.RANDOM_PORT) TestRestTemplate will resolve relative links to the running server.

This works when calling TestRestTemplate with a String parameter for the uri. When using the methods that take a java.net.URI I get org.apache.http.ProtocolException: Target host is not specified

bug

Most helpful comment

I have the same issue. I want to use TestRestTemplateto send a POST with some headers, and have to use RequestEntity, which only accepts URI.

Should RequestEntityhave methods that accepts String, or should TestRestTemplateperhaps accept headers etc?

UPDATE: I found a way to do it, it should probably still be better documented:

MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.set(...);

HttpHeaders headers = new HttpHeaders();
headers.add(...);

HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(form, headers);

ResponseEntity<String> resoinse= template.exchange("/path", POST, httpEntity, String.class);

All 5 comments

We use Spring's UriTemplateHandler so unfortunately I don't think there's an easy way to expand links that are passed in as URIs. Are you using URIs for any specific reason? Anything preventing you switching to the String version?

In my case I am using URIs because of cleaner construction (using UriComponentsBuilder). I have an easy workaround by calling uri.toString() so it's not a major issue for me. It just seems to be strange behavior from an API perspective. If it can't be fixed it should at least be documented somewhere.

@shollander Yeah, totally agree. Thanks.

I have the same issue. I want to use TestRestTemplateto send a POST with some headers, and have to use RequestEntity, which only accepts URI.

Should RequestEntityhave methods that accepts String, or should TestRestTemplateperhaps accept headers etc?

UPDATE: I found a way to do it, it should probably still be better documented:

MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
form.set(...);

HttpHeaders headers = new HttpHeaders();
headers.add(...);

HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(form, headers);

ResponseEntity<String> resoinse= template.exchange("/path", POST, httpEntity, String.class);

Nice, thanks @wilkinsona

Was this page helpful?
0 / 5 - 0 ratings