restTemplate交换通常会导致400错误

时间:2018-12-21 10:04:05

标签: java android spring rest resttemplate

在我的Android应用中,我尝试通过restTemplate.exchange发出GET请求,但它经常导致400错误,很少是200错误。

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

我尝试使用编码和解码参数进行请求,但这是相同的问题。唯一改变的是请求中的时间戳。我不认为这是一个后端问题,因为我在同一界面上通过Swagger和Postman提出了几个请求,并且所有请求都没有问题。我还尝试将spring-android更新到版本2.0.0.M3,但仍然是相同的问题。

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

设置令牌

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

这是请求在android分析器中的样子

enter image description here

这是请求是用招摇发送的样子

enter image description here

1 个答案:

答案 0 :(得分:1)

使用新的HttpEntity(headers); (没有“参数”)

“参数”字符串是根据HttpEntity documentation的请求正文 可能导致问题的原因。