I use spring-web 6.1.1. Below is working for RestTemplate
RestTemplate restTemplate = new RestTemplate();
String url = "https://dev-test.com/token";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("username", "aaa");
map.add("password", "bbc");
map.add("grant_type", "password");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request, String.class );
When using new RestClient, I got the error:
RestClient test = RestClient.builder()
.baseUrl("https://dev-test.com/")
.build();
ResponseEntity responseLicenseCheck = test.post()
.uri("/token")
.body(request)
.retrieve()
.toEntity(String.class);
--
Exception in thread "main" org.springframework.web.client.HttpClientErrorException$BadRequest: 400 Bad Request: "{"error":"unsupported_grant_type"}"
at org.springframework.web.client.HttpClientErrorException.create(HttpClientErrorException.java:103)
restClient is different with restTemplate on body() method, you need to pass data object to it instead of requestEntity, and declare headers separately. In your example:
ResponseEntity responseLicenseCheck = test.post()
.uri("/token")
.body(map)
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.retrieve()
.toEntity(String.class);
or
ResponseEntity responseLicenseCheck = test.post()
.uri("/token")
.body(map)
.headers(headers->headers.addAll(xxxxList))
.retrieve()
.toEntity(String.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With