0

In my Android app I try to make a POST via restTemplate.postForEntity() but the first time I try to post the data I get a 400 error. After my timetrigger sync-method try to post the data again it works and I get 200. 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.

This is the error I get:

POST request for "<url>" resulted in 400 (); invoking error handler org.springframework.web.client.HttpClientErrorException: 400

This is what I see at the postForEntity() when I'm debugging: 'java.lang.NullPointerException' Cannot evaluate org.springframework.http.ResponseEntity.toString()

This is the code:

public ResponseEntity<ArrayList> postServiceData(List<BasicService> attributes) {
    HttpStatus status = null;
 ResponseEntity<ArrayList> chargerServiceResponse = new ResponseEntity<ArrayList>(status);
    try {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        HttpEntity<?> entity = RestServiceUtils.getHttpEntity(attributes, context);
        chargerServiceResponse = restTemplate.postForEntity(url, entity, ArrayList.class);
        SynchronisationStorage synchronisationStorage = new SynchronisationStorage(context);
        synchronisationStorage.updateLastSynchronisationDate();
        loggingStorageDbHelper.logSuccess(R.string.logging_save_send_charger_service_to_backend, 1000);
    } catch (HttpClientErrorException e) {
      /* do stuff*/
    }
}

To set the body and token:

@NonNull
public static HttpEntity<?> getHttpEntity(List attributes, Context context) {
    HttpHeaders headers = new HttpHeaders();
    try {
        headers.set(ServiceAppConstants.HEADER_ACCEPT, ServiceAppConstants.MEDIATYPE_JSON);
        UserStorage userStorage = new UserStorage(context);
        String token = userStorage.getJsonWebToken();
        headers.set(ServiceAppConstants.HEADER_SECURITY_TOKEN, token);
    }catch (Exception ex){
        Log.e(RestServiceUtils.class.getName(), "Exception ocurred while trying to set token to header", ex);
    }
    return new HttpEntity<Object>(attributes, headers);
}
WeSt
  • 889
  • 5
  • 14
  • 32

0 Answers0