3

So I read through many questions on SO and still would want to ask this. I have a webview in my fragment. I am calling a url and want to know HTTP status code (success or failure). I have extended a class from WebViewClient class and below is snippet of the same.

I came across this method:

@Override
    public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
        super.onReceivedHttpError(view, request, errorResponse);
        if (Build.VERSION.SDK_INT >= 21){
            Log.e(LOG_TAG, "HTTP error code : "+errorResponse.getStatusCode());
        }

        webviewActions.onWebViewReceivedHttpError(errorResponse);
    }

as you can see, I have put a check

Build.VERSION.SDK_INT >= 21 since errorResponse.getStatusCode()

method is supported since API 21. But what if I want this status code before API 21? Then I found below code:

@SuppressWarnings("deprecation")
    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        Toast.makeText(context, "error code : "+errorCode+ "\n description : "+description, Toast.LENGTH_SHORT).show();
        if (errorCode == -2){
            Log.e(LOG_TAG, "error code : "+errorCode+ "\n description : "+description);
            redirectToHostNameUrl();
        }
    }

This method is deprecated and hence I had to use the annotation. Here, in 'errorCode' I get value -2 for HTTP code 404. This I took as workaround. But what if I want to avoid using this deprecated method. Kindly suggest. Thanks.

Rahul Ahuja
  • 812
  • 10
  • 24

1 Answers1

2

Method onReceivedHttpError only support for API >= 23, you can using onReceivedError to support for API below 21 and above 21.

    @TargetApi(Build.VERSION_CODES.M)
    @Override
    public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
        onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
    }

    @SuppressWarnings("deprecation")
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        if (errorCode == -14) // -14 is error for file not found, like 404.
            view.loadUrl("http://youriphost");
    }

More detail https://developer.android.com/reference/android/webkit/WebViewClient.html#ERROR_FILE

Andi Susilo
  • 121
  • 3