1

I need to send get request to example.com/api with query param named test[] For this i use spring rest tepmlate

UriComponentsBuilder builder = UriComponentsBuilder
                .fromUriString(example.com/api)
                .queryParam(test[], "test");

responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET,
                    new HttpEntity<>(this.setHttpHeader()),
                    new ParameterizedTypeReference<List<MyDTO>>() {
                    });

But builder.toUriString() return example.com/api?test%5B%5D=test I try to replace srting with my method

private String repairUri(String uri) {
        return url.replaceAll("%5B%5D", "[]");
    }

and call

responseEntity = restTemplate.exchange(repairUri(builder.toUriString()), HttpMethod.GET,
                    new HttpEntity<>(this.setHttpHeader()),
                    new ParameterizedTypeReference<List<MyDTO>>() {
                    });

But into restTemplate.exchange() this uri convert to example.com/api?test%5B%5D=test again.

Meanwhile i easy send example.com/api?test[]=test request by POSTMan and it's work.

How Can i send request to example.com/api?test[]=test in Spring?

  • ..spring does well. It is called ["url encoding"](https://en.wikipedia.org/wiki/Percent-encoding) and is "standrad"/recommendation for URL/I/N s. – xerx593 Feb 08 '21 at 16:55
  • Misnamed method: `setHttpHeader()` should be `getHttpHeaders()`, i.e. `get`, not `set`, and plural. – Andreas Feb 08 '21 at 17:03

2 Answers2

2

I find one solution. In my restTemplate bean definition I add this settings:

public RestTemplate myRestTemplate() {

    RestTemplate restTemplate = restTemplate(timeout);

    DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
    builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);
    restTemplate.setUriTemplateHandler(builderFactory);
    restTemplate.setErrorHandler(new RestClientResponseExceptionHandler());

    return restTemplate;
}

In this page some guys says that DefaultUriBuilderFactory.EncodingMode.NONE is also suitable. Read more in link.

0

Just change your repairUri method to this when you call restTemplate.exchange to this :

responseEntity = restTemplate.exchange(URLDecoder.decode(builder.toUriString(), "UTF-8"), HttpMethod.GET,
                new HttpEntity<>(this.setHttpHeader()),
                new ParameterizedTypeReference<List<MyDTO>>() {
                });
Diaf Badreddine
  • 550
  • 5
  • 8
  • Thank you for advice, it's good. But inside `restTemplate.exchange` uri `example.com/api?test[]=test` still converted to `example.com/api?test%5B%5D=test` – Pavel Bukhalov Feb 08 '21 at 16:29