Get HTTP Status Code in Android WebView

Solution 1:

It's not possible (as of the time i'm writing this). The docs for onReceiveError() are ambiguous at best, but it you look at this issue,

http://code.google.com/p/android/issues/detail?id=968

It's clear that HTTP status codes won't be reported through that mechanism. How it's possible that the developers wrote WebView with no way to retrieve the HTTP status code really blows my mind.

Solution 2:

You can load content with ajax and then just put it into the webview with loadDataWithBaseURL.

Create a web page like this

<script type="text/javascript">
    function loadWithAjax() {
        var httpRequest = new XMLHttpRequest();
        var path = 'PATH';
        var host = 'HOST';
        var url = 'URL';

        httpRequest.onreadystatechange = function(){
            if (httpRequest.readyState === 4) { 
                if (httpRequest.status === 200) {
                    browserObject.onAjaxSuccess(host, url, httpRequest.responseText);
                } else {
                    browserObject.onAjaxError(host, url, httpRequest.status);
                }
            }
        };

        httpRequest.open('GET', path, true);
        httpRequest.send(null);
    }
</script>
<body onload="loadWithAjax()">

browserObject is java object injected into javascript.

addJavascriptInterface(this, "browserObject");

And load it into webView. You should replace path/url with your values.

ajaxHtml = IOUtils.toString(getContext().getAssets().open("web/ajax.html"));
            ajaxHtml = ajaxHtml.replace("PATH", path);
            ajaxHtml = ajaxHtml.replace("URL", url);
            ajaxHtml = ajaxHtml.replace("HOST", host);

loadDataWithBaseURL(host, ajaxHtmlFinal, "text/html", null, null);

Then handle onAjaxSuccess/onAjaxError like this:

    public void onAjaxSuccess(final String host, final String url, final String html)
    {
        ((Activity) getContext()).runOnUiThread(new Runnable()
        {
            @Override
            public void run()
            {
                loadDataWithBaseURL(url, html, "text/html", null, null);
            }
        });
    }

    public void onAjaxError(final String host, final String url, final int errorCode)
    {

    }

Now you can handle http errors.

Solution 3:

You can override method onReceivedHttpError and there you can see the status code:

@Override
public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
    super.onReceivedHttpError(view, request, errorResponse);
    int statusCode = errorResponse.getStatusCode();
    // TODO: do your logic..
}