Search code examples
javaandroidspringrestresttemplate

restTemplate exchange often leads into 400 Error


In my Android app I try to make a GET request via restTemplate.exchange but it leads very often into a 400 error very seldom it's a 200 response.

GET request for "http://someURL/items/modified/2018-12-20T12%253A47%253A43%252B01%253A00" resulted in 400 (); invoking error handler

org.springframework.web.client.HttpClientErrorException: 400

I tried to do the request with encoded and decoded parameter but it's the same problem. The only thing what changes is the timestamp in the request. I don't think it's a backend problem, because I did a couple requests via Swagger and Postman on the same interface and all of them worked without a problem. I also tried to update spring-android to version 2.0.0.M3 but still the same problem.

String url = ServiceAppConstants.HOSTNAME + ServiceAppConstants.REST_ITEMS_MODIFIED +                             URLEncoder.encode(lastSynchronisationDate);
try {
  HttpEntity<String> httpEntity = RestServiceUtils.getHttpEntity(context);
  RestTemplate restTemplate = new RestTemplate();
  restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

   // runs in the error here
   ResponseEntity<ArrayList> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, ArrayList.class); 
   items= response.getBody();
   items = mapper.convertValue(items, new TypeReference<List<Items>>(){});
} catch (RestClientException e) {
    /* do stuff */
}

to set the token

@NonNull
public static HttpEntity<String> getHttpEntity(Context context) {
    UserStorage userStorage = new UserStorage(context);
    HttpHeaders headers = new HttpHeaders();
    try {
        String token = userStorage.getJsonWebToken();
        headers.set(ServiceAppConstants.HEADER_SECURITY_TOKEN, token);
    }catch (Exception ex){
        Log.e(RestServiceUtils.class.getName(), "Could not get json web token", ex);
    }
    return new HttpEntity<String>("parameters", headers);
}

This is how the request looks like in the android profiler

enter image description here

This is how the request looks like if it's send by swagger

enter image description here


Solution

  • use new HttpEntity(headers); (without "parameters")

    the "parameters" string is the request body according to HttpEntity documentation that might caused the problem.