Pavel Bukhalov
Pavel Bukhalov

Reputation: 73

How send request with query parameter "test[]=test" in spring?

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?

Upvotes: 1

Views: 891

Answers (2)

Pavel Bukhalov
Pavel Bukhalov

Reputation: 73

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.

Upvotes: 2

Diaf Badreddine
Diaf Badreddine

Reputation: 628

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>>() {
                });

Upvotes: 0

Related Questions