Encode query parameters with Uri Components Builder in spring

environment

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.0.RELEASE</version>
	</parent>

Encoding instructions

Instruct encoding with encode </ code>.

URI target = UriComponentsBuilder.newInstance()
        .scheme("http")
        .host("example.com")
        .queryParam("foo", "b&r")
        .build()
        .encode()
        .toUri();
System.out.println(target);// http://example.com?foo=b%26r

To use fromUri </ code> in the encoded URL, specify true </ code> in build (boolean encoded) </ code>.

URI source = new URI("http://example.com?foo=b%26r");
URI target = UriComponentsBuilder
        .fromUri(source)
        .build(true)
        .toUri();
System.out.println(target);// http://example.com?foo=b%26r

I was addicted to

If encode </ code> is not specified, no encoding will be performed.

URI target = UriComponentsBuilder.newInstance()
        .scheme("http")
        .host("example.com")
        .queryParam("foo", "b&r")
        .build()
        .toUri();
System.out.println(target); // http://example.com?foo=b&r

If you pass an encoded URL with fromUri </ code> and do not specify true </ code> for build (boolean encoded) </ code>, encoding will be done. Therefore, as a result, double encoding </ b> is performed.

URI source = new URI("http://example.com?foo=b%26r");
URI target = UriComponentsBuilder
        .fromUri(source)
        .build()
        .toUri();
System.out.println(target);// http://example.com?foo=b%2526r

reference

[SPR-14256] Doc: UriComponentsBuilder does not encode query parameters - Spring JIRA