gpt4 book ai didi

android - 使用 SpringFramework Android Rest Client 出现 422 错误时获取 Web 服务消息

转载 作者:太空狗 更新时间:2023-10-29 13:29:33 26 4
gpt4 key购买 nike

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

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

但是,网络服务也会返回一个像这样的 JSON 字符串:

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

即使得到了Exception,如何获取?

最佳答案

你应该 catch 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
}

}

查看 RestTemplate 的 javadocs , RestClientException .

关于android - 使用 SpringFramework Android Rest Client 出现 422 错误时获取 Web 服务消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17337737/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com