如果出现错误,如何使用Spring resttemplate和androidannotations从HttpResponse获取标头?
我知道如何在没有错误的情况下获取它们但我在错误情况下需要它们,因为我想使用的api发送一个minorstatuscode来清除httpstatuscode。
答案 0 :(得分:1)
基本上我找到了解决方案。
RestClient
@Rest(rootUrl = "https://proji.at/japi/v1", converters = { MappingJackson2HttpMessageConverter.class }, interceptors = { HttpBasicAuthenticatorInterceptor.class })
public interface ProjiRestClient extends RestClientErrorHandling {
RestTemplate getRestTemplate();
}
ErrorHandler:
@EBean
public class ProjiResponseErrorHandler implements ResponseErrorHandler {
private static final String TAG = "ProjiResponseErrorHandler";
@Override
public void handleError(ClientHttpResponse response) throws IOException {
int minor = 0;
try {
minor = Integer.parseInt(response.getHeaders(). getFirst("minor"));
} catch (Exception e) {
// TODO: handle exception
}
Log.i(TAG, "Response statuscode: " + response.getStatusCode() + " minor: "
+ response.getHeaders().getFirst("minor"));
throw new HttpMethodException(response.getStatusCode().value(), minor);
}
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
Log.i(TAG, "Response statuscode: " + response.getStatusCode());
if (response.getStatusCode().value() >= 400) {
return true;
}
return false;
}
}
使用RestClient的片段:
@RestService
ProjiRestClient restClient;
@Bean
ProjiResponseErrorHandler projiErrorhandler;
@AfterInject
void afterInject() {
restClient.getRestTemplate().setErrorHandler(projiErrorhandler);
}
然后你去调用restClient中的方法。
ResponseEntity<User> respone = restClient.getAuth(auth);
如果有人知道更好的解决方案,我很高兴听到它。