使用SpringFramework Android Rest Client收到422错误时获取Web服务消息

时间:2013-06-27 07:59:36

标签: android rest http-post

我正在开发一个连接到Web服务的Android应用程序。从Web服务我收到此错误:

POST request for "xxx" resulted in 422 (Unprocessable Entity); invoking error handler

我正在使用适用于Android的SpringFramework Rest Client,并使用以下代码连接到Web服务:

public static User sendUserPersonalData(User userProfileData)
{
    try
    {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(new MediaType("application","json")));
        HttpEntity<User> requestEntity = new HttpEntity<User>(userProfileData, requestHeaders);

        GsonHttpMessageConverter messageConverter = new GsonHttpMessageConverter();
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(messageConverter);

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setReadTimeout(readTimeout);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        restTemplate.setMessageConverters(messageConverters);

        String url = URL_BASE_WEB + USER_PERSONAL_DATA_CALL;
        ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, User.class);

        return responseEntity.getBody();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
    return null;
}

但是,Web服务还会返回一个类似这样的JSON字符串:

{
    "email": [
        "is invalid"
    ],
    "birthday": [
        "is invalid"
    ],
    "startday": [
        "is invalid"
    ],
    "sex_preference": [
        "can't be blank"
    ],
    "password": [
        "is too long (maximum is 4 characters)"
    ]
}

即使我收到异常,我怎么能得到它?

2 个答案:

答案 0 :(得分:2)

你应该像这样抓住RestClientException

  try{
     ....
     restTemplate.exchange(...);
  }catch(RestClientException e){
     //process exception
     if(e instanceof HttpStatusCodeException){
         String errorResponse=((HttpStatusCodeException)e).getResponseBodyAsString();
         //now you have the response, construct json from it, and extract the errors
     }

  }

查看RestTemplateRestClientException的javadoc。

答案 1 :(得分:0)

我对此的处理方法是添加多个catch,以确保处理每个错误。

还要注意:

  1. 为此您记录的内容是因为响应已转义为Java字符(例如:/ u733),因此可以使用 StringEscapeUtils.unescapeJava(),如以下示例所示

    < / li>
  2. 由于您必须处理有问题的响应(可以说不稳定),因此还会捕获 HttpMessageNotReadableException ,当响应中存在意外对象时就会发生。

try {
          return restTemplate.postForObject(url, request, responseType, uriVariables);
      }catch(HttpStatusCodeException e) {
          String errorResponse = e.getResponseBodyAsString();
          LOG.error("RestResponse: {}", StringEscapeUtils.unescapeJava(errorResponse));
          throw e;
      } catch (HttpMessageNotReadableException e) {
          LOG.error("Unexpected object in the response", e);
          throw e;
      }catch (Exception e){
          LOG.error("Unexpected error", e);
          throw new InvalidDataException("Unexpected error");
      }