2017-08-13 72 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

支持