0

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;
    }
W. Silva
  • 1
  • 1

1 Answers1

0

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();
Roberto Petrilli
  • 711
  • 1
  • 8
  • 22
  • It's not working for me, the same error. In content type of request have this: application/x-www-form-urlencoded;charset=UTF-8 – W. Silva Sep 29 '22 at 16:02
  • Have you tested the request with an external tool such as Postman or curl to make sure that the server works as you expect? Check also the return type in my example is a json response – Roberto Petrilli Sep 29 '22 at 16:52
  • Yes, the server response is a json and the server is working expect – W. Silva Sep 29 '22 at 17:23
  • try to map a generic Json object as return type ResponseEntity response = restTemplate.postForEntity( tokenUrl, request , ObjectNode.class ); If it down't work try to map a Generic String ResponseEntity response = restTemplate.postForEntity( tokenUrl, request , String.class ); – Roberto Petrilli Sep 29 '22 at 19:20