RestTemplate - 415 UNSUPPORTED_MEDIA_TYPE Error

612 views Asked by At

I want to call a REST service from my application. I'm not passing any request to this call. But I can't figure out from where it comes from?

    RestTemplate restTemplate = new RestTemplate();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();

        map.add("username", bonitaUsername);
        map.add("password", bonitaPassword);
        map.add("redirect", "false");

        HttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
        HttpMessageConverter stringHttpMessageConverternew = new StringHttpMessageConverter();
        List<HttpMessageConverter<?>> converters = new ArrayList<>();
        converters.add(formHttpMessageConverter);
        converters.add(stringHttpMessageConverternew);
        restTemplate.setMessageConverters(converters);

        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
        ResponseEntity<?> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        List<String> cookies = response.getHeaders().get("Set-Cookie");

        String cookieString = "";

        for (String cookie : cookies) {
            System.out.println();
            cookieString += cookie.split(";")[0] + "; ";
        }

        return cookieString;
1

There are 1 answers

0
Dasun On BEST ANSWER

This happens due to the mismatch of content types which passing to REST template. Please make sure to send the correct content type. Some times we are receiving JSON request but we need to send as another format.