Spring RestTemplate exchange DELETE with body jdk 1.8

10,144

HTTP DELETE request with body works fine with rest template for Spring 4.2 release. There could be some issue with request body you are sending to your service. Can you check "jsonInString" if it is forming correct json payload.Check the headers as well for "application/json" type. You can verify your service using Postman by sending DELETE request.

Share:
10,144

Related videos on Youtube

mrmoor
Author by

mrmoor

Updated on June 04, 2022

Comments

  • mrmoor
    mrmoor almost 2 years

    I'm trying to do a HTTP DELETE request with body with Spring RestTemplate via exchange method but I always get a 400 Bad Request like this question. With JavaScript and other tools it is posible to make this API call with DELETE. I know java <1.8 doesent support DELETE with body, but with 1.8 it should be able: see here. I'm using spring-web-4.2.6.RELEASE with jdk 1.8 so I think there must be a way.

    My code:

    public DealResponse closePosition(DealCloseRequest dealCloseRequest) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            //Object to JSON in String
            String jsonInString = mapper.writeValueAsString(dealCloseRequest);
    
            HttpEntity<String> entity = new HttpEntity<String>(jsonInString, this.headers);
            //execute request
            ResponseEntity<DealResponse> response = restTemplate.exchange("https://" + this.domain + "/gateway/deal/positions/otc", HttpMethod.DELETE, entity, DealResponse.class);
            //return filled DealResponse object
            return response.getBody();
        } catch (JsonProcessingException e) {
            this.logger.warn("could not close Position because: "+e);
            return null;
        }
    }
    

    Error message:

    org.springframework.web.client.HttpClientErrorException: 400 Bad Request
    

    Does anyone know a way to do this with spring restTemplate?