Search code examples
springsalesforceresttemplate

400 Bad Request for Spring RestTemplate and GET on Salesforce.com Connected Apps


Having an issue to create a basic API to the Salesforce.com object queries using Connected Apps and a Spring RestTemplate client. The inital authentication step using a POST operation is working fine and returns the Salesforce instance URL as well as the required access-token. The following GET operation fails with an Error 400. The URL and access-token were both validated by a Chrome POSTMAN plugin, that in combination returns a valid JSON response.

It is also worth to mention that the traditional implementation has not worked well and that "setAccept" was a later attempt to try to solve the parsing of the mediatype.

Below the code in error:

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.parseMediaType("application/json")));
headers.add("User-Agent", USER_AGENT);
headers.add("Authorization", "Bearer " + accessToken);

HttpEntity<String> request = new HttpEntity<String>(headers);

ResponseEntity<String> responseBodyForGet = restRetrieveSalesforceData
.exchange(url, HttpMethod.GET, request, String.class); 

The solution found to fix the 400 bug at the Spring RestTemplate GET operation is the following:

URI targetUrl = UriComponentsBuilder.fromUriString(url).build().toUri();

HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + accessToken);

HttpEntity<String> request = new HttpEntity<String>(headers);

logger.info("Requesting GET from: " + url);

ResponseEntity<String> responseBodyForGet = restRetrieveSalesforceData.exchange(targetUrl,
HttpMethod.GET, request, String.class); 

Solution

  • I've added the solution to the report posted above. Observe the use of the first statement UriComponentsBuilder, which solved the 400 issue at the GET.