使用SpringFramework Android Rest客户端收到422错误时获取web服务消息
我正在开发一个连接到Web服务的Android应用程序。从web服务中,我得到以下错误:使用SpringFramework Android Rest客户端收到422错误时获取web服务消息,android,rest,http-post,Android,Rest,Http Post,我正在开发一个连接到Web服务的Android应用程序。从web服务中,我得到以下错误: POST request for "xxx" resulted in 422 (Unprocessable Entity); invoking error handler 我正在使用SpringFramework Rest Client for Android,我使用以下代码连接到web服务: public static User sendUserPersonalData(User userProfile
POST request for "xxx" resulted in 422 (Unprocessable Entity); invoking error handler
我正在使用SpringFramework Rest Client for Android,我使用以下代码连接到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;
}
即使出现异常,我如何获取它?您应该像这样捕获:
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
}
}
请看一看javadocs,。我的方法是添加多个捕获,以确保每个错误都得到处理 还要注意:
从你的
OneRorListener
或类似的东西发布一些代码。我没有OneRorListener
。我没有更多的代码。为什么不捕获(HttpStatusCodeException hsce)?
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
}
}
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");
}