restTemplate postForEntity有时会导致400错误

时间:2019-01-09 10:04:33

标签: java android spring rest resttemplate

在我的Android应用中,我尝试通过restTemplate.postForEntity()进行POST,但是第一次尝试发布数据时,出现400错误。经过我的timetrigger同步方法尝试再次发布数据后,我可以得到200。我不认为这是一个后端问题,因为我在同一界面上通过Swagger和Postman进行了几次请求,但所有请求都没有问题。

这是我得到的错误:

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

这是我调试时在postForEntity()上看到的内容: 'java.lang.NullPointerException' Cannot evaluate org.springframework.http.ResponseEntity.toString()

这是代码:

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*/
    }
}

设置正文和令牌:

@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);
}

0 个答案:

没有答案