2017-08-13 98 views
3

所以我通读了很多关于SO的问题,仍然想问一下。我在我的片段中有一个webview。我正在调用一个url并想知道HTTP状态码(成功或失败)。我从WebViewClient类扩展了一个类,下面的代码片段也是一样的。HTTP状态码webview android,WebViewClient

我碰到这种方法来:

@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); 
    } 

你可以看到,我已经把支票

Build.VERSION.SDK_INT> = 21 因为 errorResponse.getStatusCode()

从API 21开始支持该方法。但是如果我想在API 21之前使用这个状态码呢?然后我发现以下代码:

@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(); 
     } 
    } 

此方法已并且因此我不得不使用注释。在这里,在'errorCode'中,我得到了值为-2的HTTP代码404。这是我采取的解决方法。但是如果我想避免使用这个弃用的方法呢。请建议。谢谢。

回答

1

方法onReceivedHttpError为API> = 23只的支持,可以使用onReceivedError为API下面21与上面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"); 
    } 

更多细节https://developer.android.com/reference/android/webkit/WebViewClient.html#ERROR_FILE

支持