Search code examples
javaspringspring-bootreplacespring-resttemplate

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?


Solution

  • 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.