W. Silva
W. Silva

Reputation: 1

MultiValueMap casuing issue application/x-www-form-urlencoded;charset=UTF-8 not supported

I need to do a request to a server. I'm using Spring Boot 2.5 and restTemplate. The endpoint consumes the MediaType application/x-www-form-urlencoded, but when request is send returns a error "endpoint only accepts application/x-www-form-urlencoded for POST requests". In debug I saw that content type send in restTemplate is: application/x-www-form-urlencoded;charset=utf-8.

Code:

 public void getToken(){
        RestTemplate restTemplate = new RestTemplate();
        
        ResponseEntity<TokenResponseDTO> responses = restTemplate
                .postForEntity(url, new HttpEntity<>(getForm(), getHeaders()), TokenResponseDTO.class);

        log.info(responses.toString());
    }

    @NotNull
    private MultiValueMap<String, String> getForm() {
        LinkedMultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("param1", "1");
        map.add("param2", "2");
        map.add("param3", "3");
        return map;
    }

    public HttpHeaders getHeaders(){
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        headers.add("header1", "aaa");
        return headers;
    }

Upvotes: 0

Views: 1154

Answers (1)

Roberto Petrilli
Roberto Petrilli

Reputation: 865

Try this approach. IN my case worked

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    
    //Forma data
    MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
    map.add("resourceServer", "ml-b2b-internet");
    map.add("client_id", clientId);
    map.add("client_secret", clientSecret);
    map.add("scope", "APP-284-PRF-77");


    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

    ResponseEntity<TokenDto> response = restTemplate.postForEntity( tokenUrl, request , TokenDto.class );

    var resp = response.getBody();

Upvotes: 0

Related Questions