Search in sources :

Example 6 with WebResourceResponse

use of android.webkit.WebResourceResponse in project weex-example by KalicyZhou.

the class WXWebView method initWebView.

private void initWebView(WebView wv) {
    WebSettings settings = wv.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.setAppCacheEnabled(true);
    settings.setUseWideViewPort(true);
    settings.setDomStorageEnabled(true);
    settings.setSupportZoom(false);
    settings.setBuiltInZoomControls(false);
    wv.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            WXLogUtils.v("tag", "onPageOverride " + url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            WXLogUtils.v("tag", "onPageStarted " + url);
            if (mOnPageListener != null) {
                mOnPageListener.onPageStart(url);
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            WXLogUtils.v("tag", "onPageFinished " + url);
            if (mOnPageListener != null) {
                mOnPageListener.onPageFinish(url, view.canGoBack(), view.canGoForward());
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
            if (mOnErrorListener != null) {
                //mOnErrorListener.onError("error", "page error code:" + error.getErrorCode() + ", desc:" + error.getDescription() + ", url:" + request.getUrl());
                mOnErrorListener.onError("error", "page error");
            }
        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
            if (mOnErrorListener != null) {
                mOnErrorListener.onError("error", "http error");
            }
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view, handler, error);
            if (mOnErrorListener != null) {
                mOnErrorListener.onError("error", "ssl error");
            }
        }
    });
    wv.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            showWebView(newProgress == 100);
            showProgressBar(newProgress != 100);
            WXLogUtils.v("tag", "onPageProgressChanged " + newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (mOnPageListener != null) {
                mOnPageListener.onReceivedTitle(view.getTitle());
            }
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) WebResourceRequest(android.webkit.WebResourceRequest) SslError(android.net.http.SslError) Bitmap(android.graphics.Bitmap) WebResourceResponse(android.webkit.WebResourceResponse) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebResourceError(android.webkit.WebResourceError) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 7 with WebResourceResponse

use of android.webkit.WebResourceResponse in project BookReader by JustWayward.

the class ReadCHMActivity method initVweView.

private void initVweView() {
    mProgressBar.setMax(100);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            visible(mProgressBar);
            mProgressBar.setProgress(newProgress);
        }
    });
    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                }
            }
            super.onPageStarted(view, url, favicon);
            mProgressBar.setProgress(50);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setProgress(100);
            gone(mProgressBar);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                }
            }
            super.onLoadResource(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                String insideFileName;
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                    insideFileName = temp;
                } else {
                    insideFileName = temp.substring(extractPath.length());
                }
                if (insideFileName.contains("#")) {
                    insideFileName = insideFileName.substring(0, insideFileName.indexOf("#"));
                }
                if (insideFileName.contains("?")) {
                    insideFileName = insideFileName.substring(0, insideFileName.indexOf("?"));
                }
                if (insideFileName.contains("%20")) {
                    insideFileName = insideFileName.replaceAll("%20", " ");
                }
                if (url.endsWith(".gif") || url.endsWith(".jpg") || url.endsWith(".png")) {
                    try {
                        return new WebResourceResponse("image/*", "", Utils.chm.getResourceAsStream(insideFileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return super.shouldInterceptRequest(view, request);
                    }
                } else if (url.endsWith(".css") || url.endsWith(".js")) {
                    try {
                        return new WebResourceResponse("", "", Utils.chm.getResourceAsStream(insideFileName));
                    } catch (IOException e) {
                        e.printStackTrace();
                        return super.shouldInterceptRequest(view, request);
                    }
                } else {
                    Utils.extractSpecificFile(chmFilePath, extractPath + insideFileName, insideFileName);
                }
            }
            Log.e("2, webviewrequest", url);
            return super.shouldInterceptRequest(view, request);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (!url.startsWith("http") && !url.endsWith(md5File)) {
                String temp = url.substring("file://".length());
                if (!temp.startsWith(extractPath)) {
                    url = "file://" + extractPath + temp;
                    view.loadUrl(url);
                    return true;
                }
            }
            return false;
        }

        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return shouldOverrideUrlLoading(view, request.getUrl().toString());
        }
    });
    mWebView.getSettings().setBuiltInZoomControls(true);
    mWebView.getSettings().setDisplayZoomControls(false);
    mWebView.getSettings().setUseWideViewPort(true);
    mWebView.getSettings().setLoadWithOverviewMode(true);
    mWebView.getSettings().setLoadsImagesAutomatically(true);
}
Also used : Bitmap(android.graphics.Bitmap) WebResourceRequest(android.webkit.WebResourceRequest) WebResourceResponse(android.webkit.WebResourceResponse) WebChromeClient(android.webkit.WebChromeClient) IOException(java.io.IOException) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 8 with WebResourceResponse

use of android.webkit.WebResourceResponse in project k-9 by k9mail.

the class K9WebViewClient method shouldInterceptRequest.

protected WebResourceResponse shouldInterceptRequest(WebView webView, Uri uri) {
    if (!CID_SCHEME.equals(uri.getScheme())) {
        return RESULT_DO_NOT_INTERCEPT;
    }
    if (attachmentResolver == null) {
        return RESULT_DUMMY_RESPONSE;
    }
    String cid = uri.getSchemeSpecificPart();
    if (TextUtils.isEmpty(cid)) {
        return RESULT_DUMMY_RESPONSE;
    }
    Uri attachmentUri = attachmentResolver.getAttachmentUriForContentId(cid);
    if (attachmentUri == null) {
        return RESULT_DUMMY_RESPONSE;
    }
    Context context = webView.getContext();
    ContentResolver contentResolver = context.getContentResolver();
    try {
        String mimeType = contentResolver.getType(attachmentUri);
        InputStream inputStream = contentResolver.openInputStream(attachmentUri);
        return new WebResourceResponse(mimeType, null, inputStream);
    } catch (Exception e) {
        Timber.e(e, "Error while intercepting URI: %s", uri);
        return RESULT_DUMMY_RESPONSE;
    }
}
Also used : Context(android.content.Context) WebResourceResponse(android.webkit.WebResourceResponse) InputStream(java.io.InputStream) Uri(android.net.Uri) ActivityNotFoundException(android.content.ActivityNotFoundException) ContentResolver(android.content.ContentResolver)

Example 9 with WebResourceResponse

use of android.webkit.WebResourceResponse in project WordPress-Android by wordpress-mobile.

the class EditorWebViewAbstract method configureWebView.

@SuppressLint("SetJavaScriptEnabled")
private void configureWebView() {
    WebSettings webSettings = this.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDefaultTextEncodingName("utf-8");
    this.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.startsWith("callback") && mJsCallbackReceiver != null) {
                String data = URLDecoder.decode(url);
                String[] split = data.split(":", 2);
                String callbackId = split[0];
                String params = (split.length > 1 ? split[1] : "");
                mJsCallbackReceiver.executeCallback(callbackId, params);
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            AppLog.e(T.EDITOR, description);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = request.getUrl().toString();
            if (!URLUtil.isNetworkUrl(url)) {
                return super.shouldInterceptRequest(view, request);
            }
            // Request and add an authorization header for HTTPS resource requests.
            // Use https:// when requesting the auth header, in case the resource is incorrectly using http://.
            // If an auth header is returned, force https:// for the actual HTTP request.
            String authHeader = mAuthHeaderRequestListener.onAuthHeaderRequested(UrlUtils.makeHttps(url));
            if (StringUtils.notNullStr(authHeader).length() > 0) {
                try {
                    url = UrlUtils.makeHttps(url);
                    // Keep any existing request headers from the WebResourceRequest
                    Map<String, String> headerMap = request.getRequestHeaders();
                    for (Map.Entry<String, String> entry : mHeaderMap.entrySet()) {
                        headerMap.put(entry.getKey(), entry.getValue());
                    }
                    headerMap.put("Authorization", authHeader);
                    HttpURLConnection conn = HTTPUtils.setupUrlConnection(url, headerMap);
                    return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(), conn.getInputStream());
                } catch (IOException e) {
                    AppLog.e(T.EDITOR, e);
                }
            }
            return super.shouldInterceptRequest(view, request);
        }

        /**
             * Compatibility method for API < 21
             */
        @SuppressWarnings("deprecation")
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (!URLUtil.isNetworkUrl(url)) {
                return super.shouldInterceptRequest(view, url);
            }
            // Request and add an authorization header for HTTPS resource requests.
            // Use https:// when requesting the auth header, in case the resource is incorrectly using http://.
            // If an auth header is returned, force https:// for the actual HTTP request.
            String authHeader = mAuthHeaderRequestListener.onAuthHeaderRequested(UrlUtils.makeHttps(url));
            if (StringUtils.notNullStr(authHeader).length() > 0) {
                try {
                    url = UrlUtils.makeHttps(url);
                    Map<String, String> headerMap = new HashMap<>(mHeaderMap);
                    headerMap.put("Authorization", authHeader);
                    HttpURLConnection conn = HTTPUtils.setupUrlConnection(url, headerMap);
                    return new WebResourceResponse(conn.getContentType(), conn.getContentEncoding(), conn.getInputStream());
                } catch (IOException e) {
                    AppLog.e(T.EDITOR, e);
                }
            }
            return super.shouldInterceptRequest(view, url);
        }
    });
    this.setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(@NonNull ConsoleMessage cm) {
            if (cm.messageLevel() == MessageLevel.ERROR) {
                if (mErrorListener != null) {
                    mErrorListener.onJavaScriptError(cm.sourceId(), cm.lineNumber(), cm.message());
                }
                AppLog.e(T.EDITOR, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            } else {
                AppLog.d(T.EDITOR, cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            }
            return true;
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            AppLog.d(T.EDITOR, message);
            if (mErrorListener != null) {
                mErrorListener.onJavaScriptAlert(url, message);
            }
            return true;
        }
    });
}
Also used : WebResourceRequest(android.webkit.WebResourceRequest) IOException(java.io.IOException) SuppressLint(android.annotation.SuppressLint) ConsoleMessage(android.webkit.ConsoleMessage) JsResult(android.webkit.JsResult) HttpURLConnection(java.net.HttpURLConnection) WebResourceResponse(android.webkit.WebResourceResponse) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) TargetApi(android.annotation.TargetApi) HashMap(java.util.HashMap) Map(java.util.Map) WebViewClient(android.webkit.WebViewClient) SuppressLint(android.annotation.SuppressLint)

Example 10 with WebResourceResponse

use of android.webkit.WebResourceResponse in project WordPress-Android by wordpress-mobile.

the class WPWebViewClient method shouldInterceptRequest.

@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String stringUrl) {
    URL imageUrl = null;
    if (mSite != null && mSite.isPrivate() && UrlUtils.isImageUrl(stringUrl)) {
        try {
            imageUrl = new URL(UrlUtils.makeHttps(stringUrl));
        } catch (MalformedURLException e) {
            AppLog.e(AppLog.T.READER, e);
        }
    }
    // Intercept requests for private images and add the WP.com authorization header
    if (imageUrl != null && WPUrlUtils.safeToAddWordPressComAuthToken(imageUrl) && !TextUtils.isEmpty(mToken)) {
        try {
            // Force use of HTTPS for the resource, otherwise the request will fail for private sites
            HttpURLConnection urlConnection = (HttpURLConnection) imageUrl.openConnection();
            urlConnection.setRequestProperty("Authorization", "Bearer " + mToken);
            urlConnection.setReadTimeout(TIMEOUT_MS);
            urlConnection.setConnectTimeout(TIMEOUT_MS);
            WebResourceResponse response = new WebResourceResponse(urlConnection.getContentType(), urlConnection.getContentEncoding(), urlConnection.getInputStream());
            return response;
        } catch (ClassCastException e) {
            AppLog.e(AppLog.T.POSTS, "Invalid connection type - URL: " + stringUrl);
        } catch (MalformedURLException e) {
            AppLog.e(AppLog.T.POSTS, "Malformed URL: " + stringUrl);
        } catch (IOException e) {
            AppLog.e(AppLog.T.POSTS, "Invalid post detail request: " + e.getMessage());
        }
    }
    return super.shouldInterceptRequest(view, stringUrl);
}
Also used : MalformedURLException(java.net.MalformedURLException) HttpURLConnection(java.net.HttpURLConnection) WebResourceResponse(android.webkit.WebResourceResponse) IOException(java.io.IOException) URL(java.net.URL)

Aggregations

WebResourceResponse (android.webkit.WebResourceResponse)11 IOException (java.io.IOException)6 WebResourceRequest (android.webkit.WebResourceRequest)4 WebView (android.webkit.WebView)4 WebViewClient (android.webkit.WebViewClient)4 Uri (android.net.Uri)3 WebChromeClient (android.webkit.WebChromeClient)3 SuppressLint (android.annotation.SuppressLint)2 TargetApi (android.annotation.TargetApi)2 Bitmap (android.graphics.Bitmap)2 WebResourceError (android.webkit.WebResourceError)2 WebSettings (android.webkit.WebSettings)2 ByteArrayInputStream (java.io.ByteArrayInputStream)2 FileNotFoundException (java.io.FileNotFoundException)2 InputStream (java.io.InputStream)2 HttpURLConnection (java.net.HttpURLConnection)2 ActivityNotFoundException (android.content.ActivityNotFoundException)1 ContentResolver (android.content.ContentResolver)1 Context (android.content.Context)1 SslError (android.net.http.SslError)1