Sending request body in GET method not working

Viewed 214

Im currently in a task in which i have to send a GET request with a body. Im a aware this isn't a good practice and that i should send the json through query params. But I'm bound to do it like this.

So let's continue. I use RestTemplate with exchange but due to SimpleClientHttpRequestFactory implementation i cannot send a body with a GET method.

RestTemplate template = new RestTemplate(new CustomClientHttpRequestFactory());
httpHeaders.setContentType(APPLICATION_JSON);
httpHeaders.set("token", token.getToken());
httpHeaders.set("companyId", companyId);
URI uri = new URI(getInspectionsUrl);

HttpEntity<InspectionsInputDTO> entity = new HttpEntity<InspectionsInputDTO>(inputDTO, httpHeaders);
response = template.exchange(uri, GET, entity, InspectionsResponseDTO.class);

After some research i found the following code:

class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {

        super.prepareConnection(connection, httpMethod);
        if ("GET".equals(httpMethod)) {
            connection.setDoOutput(true);
        }
    }
}
// RestTemplate initialization
RestTemplate template = new RestTemplate(new CustomClientHttpRequestFactory());

This tries to override SimpleClientHttpRequestFactory httpMethod allowance but id does not work. The question is, how can i send a Request BODY in GET request with RestTemplate. Maybe there is another way to override SimpleClientHttpRequestFactory. Im new in this strange world of spring, sorry if im saying something wrong (:

0 Answers
Related