Getting 400 BAD Request Using Spring RestTemplate for POST

Can someone please help me figure out what is wrong with the code below?

I am using Spring 3.1.1 RestTemplate to try calling REST WS on Box.com to get a new access token from the update token.

The code below returns 400 (BAD REQUEST) . I can successfully call the same method using the FireFox POST plugin. I compared the output of the writeForm method with the FormHttpMessageConverter class and just like I send it from FireFox.

Does anyone have any ideas?

 public static void main(String[] args) throws InterruptedException { try { String apiUrl = "https://www.box.com/api/oauth2/token"; String clientSecret = "[MY SECRET]"; String clientId = "[MY ID]"; String currentRefreshToken = "[MY CURRENT VALID REFRESHTOKEN]"; RestTemplate restTemplate = new RestTemplate(); List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>(); messageConverters.add(new FormHttpMessageConverter()); restTemplate.setMessageConverters(messageConverters); MultiValueMap<String, String> body = new LinkedMultiValueMap<String, String>(); body.add("grant_type", "refresh_token"); body.add("refresh_token", currentRefreshToken); body.add("client_id", clientId); body.add("client_secret", clientSecret); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); headers.add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/json"); headers.add("Accept-Encoding", "gzip, deflate"); HttpEntity<?> entity = new HttpEntity<Object>(body, headers); restTemplate.exchange(apiUrl, HttpMethod.POST, entity, String.class); } catch (Exception ex) { System.out.println("ex = " + ex.getMessage()); } } } 
+4
source share
2 answers

The no-arg constructor for RestTemplate uses the java.net API for requests that does not support gzip encoding. There is, however, a constructor that accepts a ClientHttpRequestFactory . You can use the HttpComponentsClientHttpRequestFactory implementation, which uses the Apache HttpComponents HttpClient API for requests. This supports gzip encoding. This way you can do something like the following (from Spring Docs ) when creating a RestTemplate :

 HttpClient httpClient = HttpClientBuilder.create().build(); ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(requestFactory); 
+3
source

In Spring Boot, adding something like this to pom.xml seems to add some magic.

 <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>retrofit</artifactId> <version>2.3.0</version> </dependency> 

I guess there are other, similar, solutions ...

0
source

Source: https://habr.com/ru/post/1486910/


All Articles