Search in sources :

Example 6 with SslError

use of android.net.http.SslError in project cyborg-core by nu-art.

the class CyborgWebView method setupClients.

private void setupClients() {
    setDownloadListener(new DownloadListener() {

        private String downloadingNow;

        @Override
        public void onDownloadStart(final String url, final String userAgent, final String contentDisposition, final String mimeType, final long contentLength) {
            logInfo("DEBUG-LOG: onDownloadStart... url: " + url + "  userAgent: " + userAgent + "  contentDisposition: " + contentDisposition + "  mimetype: " + mimeType + "  contentLength: " + contentLength);
            if (downloadingNow != null) {
                logWarning("DOWNLOAD IN PROGRESS: " + downloadingNow + "... NOT DOWNLOADING FILE FROM NEW URL: " + url);
                return;
            }
            if (downloadHandler == null) {
                if (getContext() instanceof Application) {
                    logWarning("APPLICATION CONTEXT FOUND!!! NOT DOWNLOADING FILE FROM: " + url);
                    return;
                }
                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                getContext().startActivity(i);
                return;
            }
            HandlerThread fileDownloader = new HandlerThread("File Downloader: " + url);
            fileDownloader.start();
            Handler handler = new Handler(fileDownloader.getLooper());
            downloadingNow = url;
            handler.post(new Runnable() {

                @Override
                public void run() {
                    FileOutputStream os = null;
                    InputStream is = null;
                    String fileName = contentDisposition;
                    if (fileName == null)
                        fileName = "unknown-file";
                    int index = fileName.indexOf("filename=\"");
                    if (index != -1)
                        fileName = fileName.substring(index + "filename=\"".length(), fileName.length() - 1);
                    fileName = fileName.replaceAll("[\\*/:<>\\?\\\\\\|\\+,\\.;=\\[\\]\\\"\\'\\^]", "_");
                    try {
                        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                        connection.setRequestProperty("User-Agent", userAgent);
                        connection.setRequestProperty("Content-Type", mimeType);
                        connection.connect();
                        is = connection.getInputStream();
                        File outputFile;
                        int counter = 0;
                        while (true) {
                            outputFile = new File(Storage.getDefaultStorage().getPath() + "/Download", fileName + (counter == 0 ? "" : "(" + counter + ")"));
                            if (!outputFile.exists())
                                break;
                        }
                        final File finalOutputFile = outputFile;
                        FileTools.createNewFile(finalOutputFile);
                        os = new FileOutputStream(finalOutputFile);
                        StreamTools.copy(is, contentLength, os, new ProgressNotifier() {

                            @Override
                            public void reportState(String report) {
                            }

                            @Override
                            public void onCopyStarted() {
                                downloadHandler.onDownloadStarted(url);
                            }

                            @Override
                            public void onProgressPercentage(double percentages) {
                                downloadHandler.onDownloadProgress(url, (float) percentages);
                            }

                            @Override
                            public void onCopyException(Throwable t) {
                                downloadHandler.onDownloadError(url, t);
                            }

                            @Override
                            public void onCopyEnded() {
                                downloadHandler.onDownloadEneded(url, finalOutputFile);
                            }
                        });
                    } catch (Exception e) {
                        downloadHandler.onDownloadError(url, e);
                    } finally {
                        downloadingNow = null;
                        if (os != null)
                            try {
                                os.close();
                            } catch (IOException ignored) {
                            }
                        if (is != null)
                            try {
                                is.close();
                            } catch (IOException ignored) {
                            }
                    }
                }
            });
        }
    });
    setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onProgressChanged... " + newProgress);
            if (pageHandler == null)
                return;
            if (newProgress >= 89)
                onPageFinished(view, view.getUrl());
            pageHandler.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReachedMaxAppCacheSize(long requiredStorage, long quota, QuotaUpdater quotaUpdater) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onRequestFocus...");
            if (pageDetailsHandler == null)
                return;
            CyborgWebView.this.onReachedMaxAppCacheSize(requiredStorage, quota, quotaUpdater);
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin, final Callback callback) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onGeolocationPermissionsShowPrompt (origin: " + origin + ", callback: " + callback + ")");
            if (geoLocationHandler == null)
                return;
            geoLocationHandler.onGeolocationPermissionsShowPrompt(origin, new Processor<GeoLocationResponse>() {

                @Override
                public void process(GeoLocationResponse res) {
                    callback.invoke(origin, res.enable, res.remember);
                    settings.setGeolocationEnabled(res.enable);
                }
            });
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            if (DEBUG)
                logInfo("DEBUG-LOG: onGeolocationPermissionsHidePrompt...");
            if (geoLocationHandler == null)
                return;
            geoLocationHandler.onGeolocationPermissionsShowPrompt();
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            if (DEBUG)
                logInfo("DEBUG-LOG: File Chooser: " + uploadMsg + ", acceptType: " + acceptType + ", capture: " + capture);
            openFileChooser(uploadMsg, acceptType);
        }

        public void openFileChooser(final ValueCallback<Uri> uploadMsg, String acceptType) {
            if (DEBUG)
                logInfo("DEBUG-LOG: File Chooser: " + uploadMsg + ", acceptType: " + acceptType);
            if (fileChooserHandler == null)
                uploadMsg.onReceiveValue(null);
            boolean handled = fileChooserHandler.openFileChooser(getUrl(), acceptType, new Processor<Uri>() {

                @Override
                public void process(Uri uri) {
                    uploadMsg.onReceiveValue(uri);
                }
            });
            if (!handled)
                uploadMsg.onReceiveValue(null);
        }

        @SuppressWarnings("unused")
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            if (DEBUG)
                logInfo("DEBUG-LOG: File Chooser: " + uploadMsg);
            openFileChooser(uploadMsg, null);
        }

        @Override
        public Bitmap getDefaultVideoPoster() {
            if (DEBUG)
                logInfo("DEBUG-LOG: getDefaultVideoPoster...");
            if (javaScriptHandler == null)
                return null;
            return videoHandler.getDefaultVideoPoster();
        }

        @Override
        public View getVideoLoadingProgressView() {
            if (DEBUG)
                logInfo("DEBUG-LOG: getVideoLoadingProgressView...");
            if (javaScriptHandler == null)
                return null;
            return videoHandler.getVideoLoadingProgressView();
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsAlert (url: " + url + ", message: " + message + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.confirm();
                return true;
            }
            return javaScriptHandler.onJsAlert(view, url, message, result);
        }

        @Override
        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsBeforeUnload (url: " + url + ", message: " + message + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.cancel();
                return false;
            }
            return javaScriptHandler.onJsBeforeUnload(view, url, message, result);
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsConfirm (url: " + url + ", message: " + message + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.cancel();
                return false;
            }
            return javaScriptHandler.onJsConfirm(view, url, message, result);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onJsPrompt (url: " + url + ", message: " + message + ", defaultValue: " + defaultValue + ", result: " + result + ")");
            if (javaScriptHandler == null) {
                result.cancel();
                return false;
            }
            return javaScriptHandler.onJsPrompt(view, url, message, defaultValue, result);
        }

        @Override
        public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onCreateWindow (isDialog: " + isDialog + ", isUserGesture: " + isUserGesture + ", resultMsg: " + resultMsg + ")");
            if (windowHandler == null)
                return false;
            return windowHandler.onCreateWindow(view, isDialog, isUserGesture, resultMsg);
        }

        @Override
        public void onCloseWindow(WebView window) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onCloseWindow...");
            if (windowHandler == null)
                return;
            windowHandler.onCloseWindow(window);
        }

        @Override
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onShowCustomView (callback: " + callback + ")");
            if (javaScriptHandler == null)
                return;
            customViewHandler.onShowCustomView(view, requestedOrientation, callback);
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {
            onShowCustomView(view, 0, callback);
        }

        @Override
        public void onHideCustomView() {
            if (DEBUG)
                logInfo("DEBUG-LOG: onHideCustomView...");
            if (javaScriptHandler == null)
                return;
            customViewHandler.onHideCustomView();
        }

        @Override
        public void onReceivedIcon(WebView view, Bitmap icon) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedIcon (icon: " + icon + ")");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onReceivedIcon(view, icon);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedTitle (title: " + title + ")");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onReceivedTitle(view, title);
        }

        @Override
        public void onReceivedTouchIconUrl(WebView view, String url, boolean precomposed) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedTouchIconUrl (url: " + url + ", precomposed: " + precomposed + ")");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onReceivedTouchIconUrl(view, url, precomposed);
        }

        @Override
        public void onRequestFocus(WebView view) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onRequestFocus...");
            if (pageDetailsHandler == null)
                return;
            pageDetailsHandler.onRequestFocus(view);
        }
    });
    setWebViewClient(new WebViewClient() {

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            if (DEBUG)
                logInfo("DEBUG-LOG: doUpdateVisitedHistory (url: " + url + ", isReload: " + isReload + ")");
            if (pageHandler == null)
                return;
            pageHandler.doUpdateVisitedHistory(view, url, isReload);
        }

        @Override
        public void onLoadResource(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onLoadResource (url: " + url + ")");
            if (pageHandler == null)
                return;
            pageHandler.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onPageFinished (url: " + url + ")");
            CyborgWebView.this.onPageFinished(view, url);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onPageStarted (url: " + url + ", favicon: " + favicon + ")");
            finishedURL = null;
            if (pageHandler == null)
                return;
            pageHandler.onPageStarted(view, url, favicon);
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedError (errorCode: " + errorCode + ", description: " + description + ", failingUrl: " + failingUrl + ")");
            if (pageHandler == null)
                return;
            pageHandler.onReceivedError(view, errorCode, description, failingUrl);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: shouldOverrideUrlLoading: " + url);
            if (url.toLowerCase().equals("about:blank"))
                return super.shouldOverrideUrlLoading(view, url);
            if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url)) {
                if (pageHandler != null && pageHandler.shouldOverrideUrlLoading(view, url))
                    return true;
                return super.shouldOverrideUrlLoading(view, url);
            }
            if (getContext() instanceof Activity && resolveUrl(url))
                return true;
            if (pageHandler != null && pageHandler.resolveNoneHttpUrl(view, url))
                return true;
            if (!(getContext() instanceof Activity))
                return true;
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(url));
                getContext().startActivity(intent);
            } catch (Throwable e) {
                logError(e);
            }
            return true;
        }

        /*
			 * requestHandler
			 */
        @Override
        public void onFormResubmission(WebView view, Message dontResend, Message resend) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onFormResubmission...");
            if (requestHandler == null)
                return;
            requestHandler.onFormResubmission(view, dontResend, resend);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedHttpAuthRequest (host: " + host + ", realm: " + realm + ")");
            if (requestHandler == null)
                return;
            requestHandler.onReceivedHttpAuthRequest(view, handler, host, realm);
        }

        @Override
        @SuppressWarnings("unused")
        public void onReceivedLoginRequest(WebView view, String realm, String account, String args) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedLoginRequest (realm: " + realm + ", account: " + account + ", args: " + args + ")");
            if (requestHandler == null)
                return;
            requestHandler.onReceivedLoginRequest(view, realm, account, args);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onReceivedSslError (error: " + error + ")");
            if (requestHandler == null)
                return;
            requestHandler.onReceivedSslError(view, handler, error);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            if (DEBUG)
                logInfo("DEBUG-LOG: shouldInterceptRequest: " + url);
            if (requestHandler == null)
                return null;
            return requestHandler.shouldInterceptRequest(view, url);
        }

        @Override
        public void onTooManyRedirects(WebView view, Message cancelMsg, Message continueMsg) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onTooManyRedirects...");
            if (requestHandler == null)
                return;
            requestHandler.onTooManyRedirects(view, cancelMsg, continueMsg);
        }

        @Override
        public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onUnhandledKeyEvent: " + event);
            if (systemHandler == null)
                return;
            systemHandler.onUnhandledKeyEvent(view, event);
        }

        @Override
        public void onScaleChanged(WebView view, float oldScale, float newScale) {
            if (DEBUG)
                logInfo("DEBUG-LOG: onScaleChanged: " + oldScale + " => " + newScale);
            if (systemHandler == null)
                return;
            systemHandler.onScaleChanged(view, oldScale, newScale);
        }

        @Override
        public boolean shouldOverrideKeyEvent(WebView view, KeyEvent event) {
            if (DEBUG)
                logInfo("DEBUG-LOG: shouldOverrideKeyEvent: " + event);
            if (systemHandler == null)
                return false;
            return systemHandler.shouldOverrideKeyEvent(view, event);
        }
    });
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) Processor(com.nu.art.core.generics.Processor) ProgressNotifier(com.nu.art.core.interfaces.ProgressNotifier) Message(android.os.Message) SslError(android.net.http.SslError) GeoLocationResponse(com.nu.art.cyborg.web.api.WebViewGeoLocationHandler.GeoLocationResponse) Activity(android.app.Activity) Uri(android.net.Uri) URL(java.net.URL) JsResult(android.webkit.JsResult) KeyEvent(android.view.KeyEvent) Bitmap(android.graphics.Bitmap) HttpURLConnection(java.net.HttpURLConnection) HttpAuthHandler(android.webkit.HttpAuthHandler) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient) InputStream(java.io.InputStream) WebViewWindowHandler(com.nu.art.cyborg.web.api.WebViewWindowHandler) SslErrorHandler(android.webkit.SslErrorHandler) Handler(android.os.Handler) HttpAuthHandler(android.webkit.HttpAuthHandler) WebViewFileChooserHandler(com.nu.art.cyborg.web.api.WebViewFileChooserHandler) WebViewJavaScriptHandler(com.nu.art.cyborg.web.api.WebViewJavaScriptHandler) WebViewVideoHandler(com.nu.art.cyborg.web.api.WebViewVideoHandler) WebViewDownloadHandler(com.nu.art.cyborg.web.api.WebViewDownloadHandler) WebViewSystemHandler(com.nu.art.cyborg.web.api.WebViewSystemHandler) WebViewGeoLocationHandler(com.nu.art.cyborg.web.api.WebViewGeoLocationHandler) WebViewPageDetailsHandler(com.nu.art.cyborg.web.api.WebViewPageDetailsHandler) WebViewCustomViewHandler(com.nu.art.cyborg.web.api.WebViewCustomViewHandler) ScriptActionErrorHandler(com.nu.art.cyborg.web.api.ScriptActionErrorHandler) WebViewPageHandler(com.nu.art.cyborg.web.api.WebViewPageHandler) WebViewRequestHandler(com.nu.art.cyborg.web.api.WebViewRequestHandler) Intent(android.content.Intent) IOException(java.io.IOException) View(android.view.View) WebView(android.webkit.WebView) SuppressLint(android.annotation.SuppressLint) IOException(java.io.IOException) ValueCallback(android.webkit.ValueCallback) Callback(android.webkit.GeolocationPermissions.Callback) HandlerThread(android.os.HandlerThread) WebResourceResponse(android.webkit.WebResourceResponse) DownloadListener(android.webkit.DownloadListener) FileOutputStream(java.io.FileOutputStream) QuotaUpdater(android.webkit.WebStorage.QuotaUpdater) Application(android.app.Application) File(java.io.File) JsPromptResult(android.webkit.JsPromptResult)

Example 7 with SslError

use of android.net.http.SslError in project habpanelviewer by vbier.

the class ClientWebView method initialize.

synchronized void initialize(final IConnectionListener cl) {
    setWebChromeClient(new WebChromeClient() {

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            if (consoleMessage.message().contains("SSE error, closing EventSource")) {
                cl.disconnected();
            }
            return super.onConsoleMessage(consoleMessage);
        }
    });
    setWebViewClient(new WebViewClient() {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (isHabPanelUrl(url)) {
                evaluateJavascript("angular.element(document.body).scope().$root.kioskMode", s -> {
                    mKioskMode = Boolean.parseBoolean(s);
                    Log.d(TAG, "HABPanel page loaded. kioskMode=" + mKioskMode);
                });
            }
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, final SslError error) {
            Log.d(TAG, "onReceivedSslError: " + error.getUrl());
            SslCertificate cert = error.getCertificate();
            if (ConnectionUtil.isTrusted(error.getCertificate())) {
                Log.d(TAG, "certificate is trusted: " + error.getUrl());
                handler.proceed();
                return;
            }
            String h;
            try {
                URL url = new URL(error.getUrl());
                h = url.getHost();
            } catch (MalformedURLException e) {
                h = getContext().getString(R.string.unknownHost);
            }
            final String host = h;
            String r = getContext().getString(R.string.notValid);
            switch(error.getPrimaryError()) {
                case SslError.SSL_DATE_INVALID:
                    r = getContext().getString(R.string.invalidDate);
                    break;
                case SslError.SSL_EXPIRED:
                    r = getContext().getString(R.string.expired);
                    break;
                case SslError.SSL_IDMISMATCH:
                    r = getContext().getString(R.string.hostnameMismatch);
                    break;
                case SslError.SSL_NOTYETVALID:
                    r = getContext().getString(R.string.notYetValid);
                    break;
                case SslError.SSL_UNTRUSTED:
                    r = getContext().getString(R.string.untrusted);
                    break;
            }
            final String reason = r;
            String c = getContext().getString(R.string.issuedBy) + cert.getIssuedBy().getDName() + "<br/>";
            c += getContext().getString(R.string.issuedTo) + cert.getIssuedTo().getDName() + "<br/>";
            c += getContext().getString(R.string.validFrom) + SimpleDateFormat.getDateInstance().format(cert.getValidNotBeforeDate()) + "<br/>";
            c += getContext().getString(R.string.validUntil) + SimpleDateFormat.getDateInstance().format(cert.getValidNotAfterDate()) + "<br/>";
            final String certInfo = c;
            new AlertDialog.Builder(ClientWebView.this.getContext()).setTitle(getContext().getString(R.string.certInvalid)).setMessage(getContext().getString(R.string.sslCert) + "https://" + host + " " + reason + ".\n\n" + certInfo.replaceAll("<br/>", "\n") + "\n" + getContext().getString(R.string.storeSecurityException)).setIcon(android.R.drawable.ic_dialog_alert).setPositiveButton(android.R.string.yes, (dialog, whichButton) -> {
                try {
                    ConnectionUtil.addCertificate(error.getCertificate());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.proceed();
            }).setNegativeButton(android.R.string.no, (dialog, whichButton) -> loadData("<html><body><h1>" + getContext().getString(R.string.certInvalid) + "</h1><h2>" + getContext().getString(R.string.sslCert) + "https://" + host + " " + reason + ".</h2>" + certInfo + "</body></html>", "text/html", "UTF-8")).show();
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, final HttpAuthHandler handler, final String host, final String realm) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(getContext()).setCancelable(false).setTitle(R.string.login_required).setMessage(getContext().getString(R.string.host_realm, host, realm)).setView(R.layout.dialog_login).setPositiveButton(R.string.okay, (dialog12, id) -> {
                EditText userT = ((AlertDialog) dialog12).findViewById(R.id.username);
                EditText passT = ((AlertDialog) dialog12).findViewById(R.id.password);
                handler.proceed(userT.getText().toString(), passT.getText().toString());
            }).setNegativeButton(R.string.cancel, (dialog1, which) -> handler.cancel());
            final AlertDialog alert = dialog.create();
            alert.show();
        }
    });
    setOnTouchListener((v, event) -> (event.getAction() == MotionEvent.ACTION_MOVE && mDraggingPrevented));
    CookieManager.getInstance().setAcceptCookie(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CookieManager.getInstance().setAcceptThirdPartyCookies(this, true);
    }
    WebSettings webSettings = getSettings();
    webSettings.setDomStorageEnabled(true);
    final IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
    getContext().registerReceiver(mNetworkReceiver, intentFilter);
}
Also used : Context(android.content.Context) WebViewDatabase(android.webkit.WebViewDatabase) ConsoleMessage(android.webkit.ConsoleMessage) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) IConnectionListener(de.vier_bier.habpanelviewer.openhab.IConnectionListener) SimpleDateFormat(java.text.SimpleDateFormat) Intent(android.content.Intent) SslErrorHandler(android.webkit.SslErrorHandler) AttributeSet(android.util.AttributeSet) WebSettings(android.webkit.WebSettings) MotionEvent(android.view.MotionEvent) CookieManager(android.webkit.CookieManager) WebViewClient(android.webkit.WebViewClient) View(android.view.View) URI(java.net.URI) Build(android.os.Build) WebView(android.webkit.WebView) TargetApi(android.annotation.TargetApi) Log(android.util.Log) WebChromeClient(android.webkit.WebChromeClient) HttpAuthHandler(android.webkit.HttpAuthHandler) ConnectivityManager(android.net.ConnectivityManager) SslError(android.net.http.SslError) MalformedURLException(java.net.MalformedURLException) IntentFilter(android.content.IntentFilter) NetworkInfo(android.net.NetworkInfo) InputType(android.text.InputType) BroadcastReceiver(android.content.BroadcastReceiver) ConnectionUtil(de.vier_bier.habpanelviewer.ssl.ConnectionUtil) AlertDialog(android.support.v7.app.AlertDialog) SharedPreferences(android.content.SharedPreferences) SslCertificate(android.net.http.SslCertificate) EditText(android.widget.EditText) AlertDialog(android.support.v7.app.AlertDialog) EditText(android.widget.EditText) SslErrorHandler(android.webkit.SslErrorHandler) IntentFilter(android.content.IntentFilter) MalformedURLException(java.net.MalformedURLException) SslError(android.net.http.SslError) ConsoleMessage(android.webkit.ConsoleMessage) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) MalformedURLException(java.net.MalformedURLException) SslCertificate(android.net.http.SslCertificate) HttpAuthHandler(android.webkit.HttpAuthHandler) WebSettings(android.webkit.WebSettings) WebChromeClient(android.webkit.WebChromeClient) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Example 8 with SslError

use of android.net.http.SslError in project IbookerEditorAndroid by zrunker.

the class MainActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ibookerEditorView = findViewById(R.id.ibookereditorview);
    ibookerEditorView.setIEEditViewBackgroundColor(Color.parseColor("#DDDDDD")).setIEEditViewIbookerEdHint("书客编辑器").setIbookerEditorImgPreviewListener(new IbookerEditorWebView.IbookerEditorImgPreviewListener() {

        @Override
        public void onIbookerEditorImgPreview(String currentPath, int position, ArrayList<String> imgAllPathList) {
            Toast.makeText(MainActivity.this, currentPath + "===" + position + "===" + imgAllPathList.toString(), Toast.LENGTH_LONG).show();
            Intent intent = new Intent(MainActivity.this, ImgVPagerActivity.class);
            intent.putExtra("currentPath", currentPath);
            intent.putExtra("position", position);
            intent.putStringArrayListExtra("imgAllPathList", imgAllPathList);
            startActivity(intent);
        }
    }).setIbookerEditorWebViewUrlLoadingListener(new IbookerEditorWebView.IbookerEditorWebViewUrlLoadingListener() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
            return true;
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setData(Uri.parse(request.getUrl().toString()));
                startActivity(intent);
            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
        }

        @Override
        public void onPageFinished(WebView view, String url) {
        }
    });
    ibookerEditorView.getIbookerEditorVpView().getEditView().getIbookerEd().setText("[链接描述](http://ips.ifeng.com/video19.ifeng.com/video09/2018/09/28/p2749834-102-998769-221938.mp4?ifsign=1&vid=2f24cc82-9236-4289-adcc-5e34ae569cc8&uid=1516537011039_hyemhv7718&from=weMedia_pc&pver=weMediaHTML5Player_v1.0.0&sver=&se=%E9%A3%9E%E7%A2%9F%E8%AF%B4&cat=8622&ptype=8622&platform=pc&sourceType=h5&dt=1538135880000&gid=SLTFYWYkO4jp&sign=16536514b3d291920ac6253872661e9c&tm=1538206173419)\n" + "                   " + "\"This come from string. You can insert inline formula:\" +\n" + "            \" \\\\(ax^2 + bx + c = 0\\\\) \" +\n" + "            \"or displayed formula: $$\\\\sum_{i=0}^n i^2 = \\\\frac{(n^2+n)(2n+1)}{6}$$\";" + "### 书客编辑器\n***\n书客编辑器从这里开始,我们的每一次开始,都那么小心翼翼,这一次如果可以的话不妨就现在开始试试。\n\n书客编辑器,简易,高效。轻轻松松记录你的每一刻。\n>书客编辑器不仅仅是为了“还好”而设计\n\n“还好”,那就意味着产品不够好;“很好”,那就意味着还需要努力;产品目标只为“最好”。\n```\nWish you every day to be beautiful.\n```\n书客编辑器期待你的加入!!!\n\n![书客编辑器](http://editor.ibooker.cc/resources/images-logos/ic_launcher_96.png)\n![书客创作](http://www.ibookerfile.cc/upload/images/acontents/1_1519218464761acontentimage.jpg)");
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) WebResourceRequest(android.webkit.WebResourceRequest) SslError(android.net.http.SslError) ArrayList(java.util.ArrayList) Intent(android.content.Intent) Bitmap(android.graphics.Bitmap) IbookerEditorWebView(cc.ibooker.ibookereditorlib.IbookerEditorWebView) WebResourceError(android.webkit.WebResourceError) IbookerEditorWebView(cc.ibooker.ibookereditorlib.IbookerEditorWebView) WebView(android.webkit.WebView)

Example 9 with SslError

use of android.net.http.SslError in project XobotOS by xamarin.

the class BrowserFrame method reportSslCertError.

/**
     * Called by JNI when the Chromium HTTP stack gets an invalid certificate chain.
     *
     * We delegate the request to CallbackProxy, and route its response to
     * {@link #nativeSslCertErrorProceed(int)} or
     * {@link #nativeSslCertErrorCancel(int, int)}.
     */
private void reportSslCertError(final int handle, final int certError, byte[] certDER, String url) {
    final SslError sslError;
    try {
        X509Certificate cert = new X509CertImpl(certDER);
        SslCertificate sslCert = new SslCertificate(cert);
        sslError = SslError.SslErrorFromChromiumErrorCode(certError, sslCert, url);
    } catch (IOException e) {
        // Can't get the certificate, not much to do.
        Log.e(LOGTAG, "Can't get the certificate from WebKit, canceling");
        nativeSslCertErrorCancel(handle, certError);
        return;
    }
    if (SslCertLookupTable.getInstance().isAllowed(sslError)) {
        nativeSslCertErrorProceed(handle);
        mCallbackProxy.onProceededAfterSslError(sslError);
        return;
    }
    SslErrorHandler handler = new SslErrorHandler() {

        @Override
        public void proceed() {
            SslCertLookupTable.getInstance().setIsAllowed(sslError);
            nativeSslCertErrorProceed(handle);
        }

        @Override
        public void cancel() {
            nativeSslCertErrorCancel(handle, certError);
        }
    };
    mCallbackProxy.onReceivedSslError(handler, sslError);
}
Also used : SslCertificate(android.net.http.SslCertificate) SslError(android.net.http.SslError) X509CertImpl(org.apache.harmony.security.provider.cert.X509CertImpl) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate)

Example 10 with SslError

use of android.net.http.SslError in project android-app-common-tasks by multidots.

the class OAuthActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.asn_activity_oauth);
    final String paramUrlToLoad = getIntent().getStringExtra(PARAM_URL_TO_LOAD);
    final String paramCallback = getIntent().getStringExtra(PARAM_CALLBACK);
    if (TextUtils.isEmpty(paramUrlToLoad)) {
        throw new IllegalArgumentException("required PARAM_URL_TO_LOAD");
    }
    if (TextUtils.isEmpty(paramCallback)) {
        throw new IllegalArgumentException("required PARAM_CALLBACK");
    }
    WebView webView = (WebView) findViewById(R.id.web_view);
    final View progressContainer = findViewById(R.id.progress_container);
    webView.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            progressContainer.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressContainer.setVisibility(View.GONE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.contains(paramCallback)) {
                Intent intent = new Intent();
                intent.setData(Uri.parse(url));
                setResult(RESULT_OK, intent);
                finish();
                return true;
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Intent intent = new Intent();
            intent.setAction(description);
            setResult(RESULT_CANCELED, intent);
            finish();
        }
    });
    webView.loadUrl(paramUrlToLoad);
}
Also used : SslErrorHandler(android.webkit.SslErrorHandler) Bitmap(android.graphics.Bitmap) SslError(android.net.http.SslError) Intent(android.content.Intent) WebView(android.webkit.WebView) View(android.view.View) WebView(android.webkit.WebView) WebViewClient(android.webkit.WebViewClient)

Aggregations

SslError (android.net.http.SslError)17 SslErrorHandler (android.webkit.SslErrorHandler)12 WebView (android.webkit.WebView)12 WebViewClient (android.webkit.WebViewClient)11 Bitmap (android.graphics.Bitmap)8 View (android.view.View)7 WebSettings (android.webkit.WebSettings)7 Intent (android.content.Intent)6 WebChromeClient (android.webkit.WebChromeClient)6 WebResourceRequest (android.webkit.WebResourceRequest)6 SslCertificate (android.net.http.SslCertificate)5 WebResourceError (android.webkit.WebResourceError)5 WebResourceResponse (android.webkit.WebResourceResponse)5 Uri (android.net.Uri)4 HttpAuthHandler (android.webkit.HttpAuthHandler)4 SuppressLint (android.annotation.SuppressLint)3 X509Certificate (java.security.cert.X509Certificate)3 Activity (android.app.Activity)2 Build (android.os.Build)2 Handler (android.os.Handler)2