我是Spring Boot 2 REST应用程序。我从Angular那里消费了REST,并且我使用Spring for Android 2.0.0M3库创建了一个Android应用程序。
通常我会这样做一个REST调用:
private class Login2 extends AsyncTask<Void, Void, ResponseEntity<JwtAuthenticationResponse>> {
private RestClientException error = null;
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
protected ResponseEntity<JwtAuthenticationResponse> doInBackground(Void... params) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
try {
String url = UtilityFunctions.getBaseUrl(LoginActivity.this) + Globle.LOGIN;
ResponseEntity<JwtAuthenticationResponse> jwtToken = restTemplate.postForEntity(url, new LoginRequest(mEditTextUserName.getText().toString(), mEditTextPassword.getText().toString()), JwtAuthenticationResponse.class);
return jwtToken;
} catch (RestClientException e) {
this.error = e;
Logcat.e(TAG, e.getMessage());
return null;
}
}
@Override
protected void onPostExecute(ResponseEntity<JwtAuthenticationResponse> response) {
//hide progress bar
mProgressBar.setVisibility(View.GONE);
if(error != null){
String title = "";
new AlertDialog.Builder(LoginActivity.this)
.setTitle(Html.fromHtml("<font color='#04C1D9'>" + title + "</font>"))
.setMessage(error.getMessage())
.setPositiveButton(getResources().getString(R.string.ok), null)
.show();
}
if (response != null) {
HttpStatus status = response.getStatusCode();
JwtAuthenticationResponse body = response.getBody();
}
}
}
服务器返回2种不同类型的例外。正常异常和验证异常。 正常的异常如下所示:
{
"timestamp": "2018-05-19T08:49:23.689+0000",
"status": 401,
"error": "Unauthorized",
"message": "Credenziali non valide. Controllare i dati inseriti e ripetere l'operazione.",
"path": "/api/v1/auth"
}
验证异常如下所示:
{
"errors" : [ {
"entity" : "Hotel",
"property" : "fax",
"invalidValue" : "+39 ",
"message" : "Il numero di telefono non è valido. Dovrebbe essere nel formato E.123 internazionale (https://en.wikipedia.org/wiki/E.123)."
} ]
}
我的Android代码效果很好,如果我不例外,但我有一个(让我们说401)RestClientException
没有从服务器返回JSON中的所有信息(在简而言之,我没有身体)。
如何使用Spring库在Android中管理类型化回复和结构化异常?