I wanna catch status code, like 401, 404, 500, etc. And handle things with different error codes. When I first used the WebView
, I thought the error code param in the onReceivedError(WebView view, int errorCode, String description, String failingUrl)
callback is what I want. But unfortunately its the constant values that defined in WebViewClient
. Yep, I have searched this question for a long time on the net, inclusive official docs and community issues: issue01, issue02, issue03, but it came to nothing. The only thing that I know is we can use onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
callback after API 23. And I wrote codes below but it didn't works on Nexus 6p(system version: Android N, minSdkVersion: 15, targetSdkVersion: 24):
private class MyWebViewClient extends WebViewClient {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
Log.d(TAG, error.getErrorCode() + ": " + error.getDescription());
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.d(TAG, failingUrl + "\t" + errorCode + ": " + description);
}
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
super.onReceivedHttpError(view, request, errorResponse);
Log.d(TAG, String.valueOf(errorResponse.getStatusCode()));
}
}
I use WebView
to load a url which needs a token, apparently it should callback the onReceivedHttpError
and get the error code 401 through the WebResourceResponse
, but there is not any log in the logcat
when I run above codes in my device.
Please help or try to give some ideas about how to achieve this. I just don't know why to mark my question duplicate and don't even give a practical answer.