Nate Hiber
Nate Hiber

Reputation: 123

Use relative path with Spring MVC RestTemplate using UriComponentBuilder

I have this. I would like to get rid from "http://localhost:8080" and use only relative path like i can do with just sending in restTemlate like

restTemplate.postForEntity("/processing/$attribute", data, Sum::class.java).body

How can i perform that with UriComponentBuilder? Here's my code:

 val builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8080/calculation/$attribute")
            .queryParam("name", name)
                .build().encode().toUri()

        return  restTemplate.postForEntity(builder, data, Sum::class.java).body

Upvotes: 0

Views: 969

Answers (1)

Fat Cat
Fat Cat

Reputation: 11

You may (and maybe even want to, in case it won't change) set "general part of path" in RestTemplate params:

val restTemplate = RestTemplate().apply {
    uriTemplateHandler = DefaultUriBuilderFactory("http://localhost:8080/calculations")
}

Then you can use UriComponentBuilder to set up a relative path:

val relativeUri = UriComponentsBuilder.fromUriString("/processing/")
        .queryParam("name", name)
        .build()
        .toUriString()

Finally, you can perform a request like:

restTemplate.postForEntity<String>(relativeUri, entity)

Upvotes: 1

Related Questions