2017-04-18 433 views
0
  1. 在我的Android應用程序中,我使用了WebView來顯示橫幅。
  2. 有旗幟佈局內的URL的數量,但沒有網址.../favicon.ico的
  3. 的WebView 自動嘗試基於我的基本URL + /favicon.ico加載的favicon.ico,得到響應404和做不加載最近RULs

如果重要:如何禁用WebView加載favicon.ico(即特定的URL)?

  • 基地URL從https://開頭...
  • 響應使用SSL證書
  • 響應具有授權

有可能防止的WebView加載圖標允許它獲得404響應後裝入其他環節additiohal頭?

webView.setWebViewClient(new WebViewClient() { 

     [email protected] onReceivedError... 

     @SuppressWarnings("deprecation") 
     @Override 
     public WebResourceResponse shouldInterceptRequest(WebView view, String url) { 
      return getNewResponse(url); 
     } 

     @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
     @Override 
     public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { 
      String url = request.getUrl().toString(); 
      return getNewResponse(url); 
     } 

     private WebResourceResponse getNewResponse(String url) { 

      try { 
       OkHttpClient client = MyOkHttpClient.getInstance(); 

       Request.Builder requestBuilder = new Request.Builder(); 
       requestBuilder.url(url.trim()) 
         .addHeader("api-key", Constants.API_KEY) 
         .addHeader("platform", Constants.PLATFORM); 

       Request request = requestBuilder.build(); 

       Response response = client.newCall(request).execute(); 

       return new WebResourceResponse(
         getMimeType(url), 
         response.header("content-encoding", "utf-8"), 
         response.body().byteStream() 
       ); 

      } catch (Exception e) { 
       return null; 
      } 

     } 

     private String getMimeType(String url) { 
      ... 
      return type; 
     } 

    }); 
+0

的可能的複製[禁用的Android web視圖/ WebViewClient啓動的favicon.ico請求](https://stackoverflow.com/questions/34886582/disable-android-webview-webviewclient-initiated-favicon-ico-request) – marmor

回答

0

是的,你可以做到這一點,但它不能在預棒棒糖設備上工作。 首先創建一個不可見的虛擬圖標,並將該圖標粘貼到您的資產文件夾中。每當獲得您可以顯示該圖標的圖標時,將下面的代碼放在下面,如果沒有,那麼您的資產文件夾會加載虛擬圖標。

@Override 
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { 
    if(!request.isForMainFrame() && request.getUrl().getPath().equals("/favicon.ico")) { 
     try { 
      return new WebResourceResponse("image/png", null, new BufferedInputStream(view.getContext().getAssets().open("dummyfavicon.ico"))); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return null; 
}