I'm developing an Android application that connects to a Web service. From the web service I get this error:
POST request for "xxx" resulted in 422 (Unprocessable Entity); invoking error handler
I'm using SpringFramework Rest Client for Android, and I connect to the web service with this code:
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;
}
But, the web service also returns a JSON string like this one:
{
"email": [
"is invalid"
],
"birthday": [
"is invalid"
],
"startday": [
"is invalid"
],
"sex_preference": [
"can't be blank"
],
"password": [
"is too long (maximum is 4 characters)"
]
}
How can I get it even if I get an Exception?
You should catch the RestClientException like this :
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
}
}
Have a look at the javadocs for RestTemplate, RestClientException.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With