不会因404错误而调用Android WebViewClient onReceivedError

gan*_*esh 10 android webview webviewclient


在列表视图中我有一个webview应该从服务器加载图像文件,当没有图像存在时,我需要一个虚拟图像.我试过

holder.image.setWebViewClient(new WebViewClient()
{
                  @Override
                public void onReceivedError( WebView view, int errorCode, String description, String failingUrl) 
                {

                    System.out.println("description error" + description);
                    view.setVisibility( View.GONE );

                }

                @Override
                public void onPageFinished(WebView view, String url) {

                    view.setVisibility( View.VISIBLE );


                }


   }); 
Run Code Online (Sandbox Code Playgroud)

我在FrameLayout中有一个虚拟图像的webview,在每个图像url加载后调用onPageFinished监听器,但是没有为产生404错误的url调用onReceivedError.任何猜测如何做.

Jus*_*ler 7

我不得不重写 WebViewClient.onReceivedHttpError() 而不是 WebViewClient.onReceivedError()。

    @Override
    public void onReceivedHttpError(final WebView view, final WebResourceRequest request, WebResourceResponse errorResponse) {
        final int statusCode;
        // SDK < 21 does not provide statusCode
        if (Build.VERSION.SDK_INT < 21) {
            statusCode = STATUS_CODE_UNKNOWN;
        } else {
            statusCode = errorResponse.getStatusCode();
        }

        Log().d(LOG_TAG, "[onReceivedHttpError]" + statusCode);
    }
Run Code Online (Sandbox Code Playgroud)

从 WebClient 文档:

/**
 * Notify the host application that an HTTP error has been received from the server while
 * loading a resource.  HTTP errors have status codes &gt;= 400.  This callback will be called
 * for any resource (iframe, image, etc), not just for the main page. Thus, it is recommended to
 * perform minimum required work in this callback. Note that the content of the server
 * response may not be provided within the <b>errorResponse</b> parameter.
 * @param view The WebView that is initiating the callback.
 * @param request The originating request.
 * @param errorResponse Information about the error occured.
 */
public void onReceivedHttpError(
        WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
}
Run Code Online (Sandbox Code Playgroud)

  • 如果 API 级别 &lt; 23,则 onReceivedHttpError 不可用 (5认同)

Mat*_*lis -1

该代码看起来是正确的;您的页面是否有可能没有生成 404 错误?