Example usage for android.webkit HttpAuthHandler proceed

List of usage examples for android.webkit HttpAuthHandler proceed

Introduction

In this page you can find the example usage for android.webkit HttpAuthHandler proceed.

Prototype

public void proceed(String username, String password) 

Source Link

Document

Instructs the WebView to proceed with the authentication with the given credentials.

Usage

From source file:com.mimo.service.api.MimoOauth2Client.java

/**
 * Instantiate a webview and allows the user to login to the Api form within
 * the application/*  ww  w  .  j a v a2s.  c o  m*/
 * 
 * @param p_view
 *            : Calling view
 * 
 * @param p_activity
 *            : Calling Activity reference
 **/

@SuppressLint("SetJavaScriptEnabled")
public void login(View p_view, Activity p_activity) {

    final Activity m_activity;
    m_activity = p_activity;
    String m_url = this.m_api.getAuthUrl();
    WebView m_webview = new WebView(p_view.getContext());
    m_webview.getSettings().setJavaScriptEnabled(true);
    m_webview.setVisibility(View.VISIBLE);
    m_activity.setContentView(m_webview);

    m_webview.requestFocus(View.FOCUS_DOWN);
    /**
     * Open the softkeyboard of the device to input the text in form which
     * loads in webview.
     */
    m_webview.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View p_v, MotionEvent p_event) {
            switch (p_event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_UP:
                if (!p_v.hasFocus()) {
                    p_v.requestFocus();
                }
                break;
            }
            return false;
        }
    });

    /**
     * Show the progressbar in the title of the activity untill the page
     * loads the give url.
     */
    m_webview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView p_view, int p_newProgress) {
            ((Activity) m_context).setProgress(p_newProgress * 100);
            ((Activity) m_context).setTitle(MimoAPIConstants.DIALOG_TEXT_LOADING);

            if (p_newProgress == 100)
                ((Activity) m_context).setTitle(m_context.getString(R.string.app_name));
        }
    });

    m_webview.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView p_view, String p_url, Bitmap p_favicon) {
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView p_view, HttpAuthHandler p_handler, String p_url,
                String p_realm) {
            p_handler.proceed(MimoAPIConstants.USERNAME, MimoAPIConstants.PASSWORD);
        }

        public void onPageFinished(WebView p_view, String p_url) {
            if (MimoAPIConstants.DEBUG) {
                Log.d(TAG, "Page Url = " + p_url);
            }
            if (p_url.contains("?code=")) {
                if (p_url.indexOf("code=") != -1) {
                    String[] m_urlSplit = p_url.split("=");

                    String m_tempString1 = m_urlSplit[1];
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "TempString1 = " + m_tempString1);
                    }
                    String[] m_urlSplit1 = m_tempString1.split("&");

                    String m_code = m_urlSplit1[0];
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "code = " + m_code);
                    }
                    MimoOauth2Client.this.m_code = m_code;
                    Thread m_thread = new Thread() {
                        public void run() {
                            String m_token = requesttoken(MimoOauth2Client.this.m_code);

                            Log.d(TAG, "Token = " + m_token);

                            Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class);

                            m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token);

                            m_activity.startActivity(m_navigateIntent);
                        }
                    };
                    m_thread.start();
                } else {
                    if (MimoAPIConstants.DEBUG) {
                        Log.d(TAG, "going in else");
                    }
                }
            } else if (p_url.contains(MimoAPIConstants.URL_KEY_TOKEN)) {
                if (p_url.indexOf(MimoAPIConstants.URL_KEY_TOKEN) != -1) {
                    String[] m_urlSplit = p_url.split("=");
                    final String m_token = m_urlSplit[1];

                    Thread m_thread = new Thread() {
                        public void run() {
                            Intent m_navigateIntent = new Intent(m_activity, MimoTransactions.class);
                            m_navigateIntent.putExtra(MimoAPIConstants.KEY_TOKEN, m_token);
                            m_activity.startActivity(m_navigateIntent);
                        }
                    };
                    m_thread.start();
                }
            }
        };
    });

    m_webview.loadUrl(m_url);
}

From source file:org.apache.cordova.CordovaWebViewClient.java

/**
 * On received http auth request./*from w  ww .  j a  v  a 2 s.  co m*/
 * The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
 *
 * @param view
 * @param handler
 * @param host
 * @param realm
 */
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {

    // Get the authentication token
    AuthenticationToken token = this.getAuthenticationToken(host, realm);
    if (token != null) {
        handler.proceed(token.getUserName(), token.getPassword());
    } else {
        // Handle 401 like we'd normally do!
        super.onReceivedHttpAuthRequest(view, handler, host, realm);
    }
}

From source file:org.apache.cordova.AndroidWebViewClient.java

/**
 * On received http auth request./*  w w w .j  a va2  s  .  co  m*/
 * The method reacts on all registered authentication tokens. There is one and only one authentication token for any host + realm combination
 */
@Override
public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {

    // Get the authentication token (if specified)
    AuthenticationToken token = this.getAuthenticationToken(host, realm);
    if (token != null) {
        handler.proceed(token.getUserName(), token.getPassword());
        return;
    }

    // Check if there is some plugin which can resolve this auth challenge
    PluginManager pluginManager = this.appView.pluginManager;
    if (pluginManager != null && pluginManager.onReceivedHttpAuthRequest(this.appView,
            new CordovaHttpAuthHandler(handler), host, realm)) {
        this.appView.loadUrlTimeout++;
        return;
    }

    // By default handle 401 like we'd normally do!
    super.onReceivedHttpAuthRequest(view, handler, host, realm);
}

From source file:org.h4des.alertrmobilemanager.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.webView = (WebView) findViewById(R.id.webView);

    // clear cache
    this.webView.clearCache(true);

    // enable JavaScript
    this.webView.getSettings().setJavaScriptEnabled(true);

    this.webView.setWebChromeClient(new WebChromeClient());

    // create own WebViewClient
    this.webView.setWebViewClient(new WebViewClient() {

        // for debugging in the emulator only
        // install your own certificate on the android device via copying your cert.cer
        // on the sd card and add it in the security options
        //@Override
        //public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {            
        //    handler.proceed();
        //}/*  w  ww. ja  v  a 2 s.com*/

        // when using basic http authentication
        // enter your own credentials
        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host,
                String realm) {

            // get username and password from the settings
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            String username = preferences.getString("username", "None");
            String password = preferences.getString("password", "None");

            // use credentials from the settings
            handler.proceed(username, password);
        }
    });

    // get URL from the settings
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    String url = preferences.getString("url", "None");

    this.webView.loadUrl(url);

    // focus webView
    this.webView.requestFocus(View.FOCUS_DOWN);
}

From source file:net.olejon.spotcommander.WebViewActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Google API client
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build();

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Hide status bar?
    if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR"))
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Power manager
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock");

    // Settings/*  ww  w.j a  v a  2  s  .c o m*/
    mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false);

    // Current network
    mCurrentNetwork = mTools.getCurrentNetwork();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    final String uri = computer[0];
    final String username = computer[1];
    final String password = computer[2];

    // Layout
    setContentView(R.layout.activity_webview);

    // Status bar color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mStatusBarPrimaryColor = getWindow().getStatusBarColor();
        mStatusBarCoverArtColor = mStatusBarPrimaryColor;
    }

    // Notification
    mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN);

    if (mPersistentNotificationIsSupported) {
        final Intent launchActivityIntent = new Intent(mContext, MainActivity.class);
        launchActivityIntent.setAction("android.intent.action.MAIN");
        launchActivityIntent.addCategory("android.intent.category.LAUNCHER");
        mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class);
        hideIntent.setAction("hide_notification");
        hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class);
        previousIntent.setAction("previous");
        previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class);
        playPauseIntent.setAction("play_pause");
        playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class);
        nextIntent.setAction("next");
        nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeDownIntent.setAction("adjust_spotify_volume_down");
        volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeUpIntent.setAction("adjust_spotify_volume_up");
        volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        mNotificationManager = NotificationManagerCompat.from(mContext);
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mNotificationBuilder.setPriority(Notification.PRIORITY_MAX);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
            mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT);
        }
    }

    // Web view
    mWebView = (WebView) findViewById(R.id.webview_webview);

    mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background));
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    mWebView.setWebViewClient(new WebViewClient() {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && !url.contains(uri)
                    && !url.contains("olejon.net/code/spotcommander/api/1/spotify/")
                    && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }

            return false;
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host,
                String realm) {
            if (handler.useHttpAuthUsernamePassword()) {
                handler.proceed(username, password);
            } else {
                handler.cancel();

                mWebView.stopLoading();

                mTools.showToast(getString(R.string.webview_authentication_failed), 1);

                mTools.navigateUp(mActivity);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest webResourceRequest,
                WebResourceError webResourceError) {
            mWebView.stopLoading();

            mTools.showToast(getString(R.string.webview_error), 1);

            mTools.navigateUp(mActivity);
        }

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

            mWebView.stopLoading();

            new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title)
                    .content(getString(R.string.webview_dialog_ssl_error_message))
                    .positiveText(R.string.webview_dialog_ssl_error_positive_button)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog,
                                @NonNull DialogAction dialogAction) {
                            finish();
                        }
                    }).contentColorRes(R.color.black).show();
        }
    });

    // User agent
    mProjectVersionName = mTools.getProjectVersionName();

    final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : "";
    final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : "";
    final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT
            && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS"))
                    ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D "
                    : "";

    // Web settings
    final WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);
    webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(),
            mProjectVersionName, uaAppend1, uaAppend2, uaAppend3));

    // Load app
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        mWebView.loadUrl(uri);
    }

    // JavaScript interface
    mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}

From source file:com.mediaexplorer.remote.MexRemoteActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);//w ww .j a  v  a  2 s. c om

    this.setTitle(R.string.app_name);
    dbg = "MexWebremote";

    text_view = (TextView) findViewById(R.id.text);

    web_view = (WebView) findViewById(R.id.link_view);
    web_view.getSettings().setJavaScriptEnabled(true);/*
                                                      /* Future: setOverScrollMode is API level >8
                                                      * web_view.setOverScrollMode (OVER_SCROLL_NEVER);
                                                      */

    web_view.setBackgroundColor(0);

    web_view.setWebViewClient(new WebViewClient() {
        /* for some reason we only get critical errors so an auth error
         * is not handled here which is why there is some crack that test
         * the connection with a special httpclient
         */
        @Override
        public void onReceivedHttpAuthRequest(final WebView view, final HttpAuthHandler handler,
                final String host, final String realm) {
            String[] userpass = new String[2];

            userpass = view.getHttpAuthUsernamePassword(host, realm);

            HttpResponse response = null;
            HttpGet httpget;
            DefaultHttpClient httpclient;
            String target_host;
            int target_port;

            target_host = MexRemoteActivity.this.target_host;
            target_port = MexRemoteActivity.this.target_port;

            /* We may get null from getHttpAuthUsernamePassword which will
             * break the setCredentials so junk used instead to keep
             * it happy.
             */

            Log.d(dbg, "using the set httpauth, testing auth using client");
            try {
                if (userpass == null) {
                    userpass = new String[2];
                    userpass[0] = "none";
                    userpass[1] = "none";
                }
            } catch (Exception e) {
                userpass = new String[2];
                userpass[0] = "none";
                userpass[1] = "none";
            }

            /* Log.d ("debug",
             *  "trying: GET http://"+userpass[0]+":"+userpass[1]+"@"+target_host+":"+target_port+"/");
             */
            /* We're going to test the authentication credentials that we
             * have before using them so that we can act on the response.
             */

            httpclient = new DefaultHttpClient();

            httpget = new HttpGet("http://" + target_host + ":" + target_port + "/");

            httpclient.getCredentialsProvider().setCredentials(new AuthScope(target_host, target_port),
                    new UsernamePasswordCredentials(userpass[0], userpass[1]));

            try {
                response = httpclient.execute(httpget);
            } catch (IOException e) {
                Log.d(dbg, "Problem executing the http get");
                e.printStackTrace();
            }

            Log.d(dbg, "HTTP reponse:" + Integer.toString(response.getStatusLine().getStatusCode()));
            if (response.getStatusLine().getStatusCode() == 401) {
                /* We got Authentication failed (401) so ask user for u/p */

                /* login dialog box */
                final AlertDialog.Builder logindialog;
                final EditText user;
                final EditText pass;

                LinearLayout layout;
                LayoutParams params;

                TextView label_username;
                TextView label_password;

                logindialog = new AlertDialog.Builder(MexRemoteActivity.this);

                logindialog.setTitle("Mex Webremote login");

                user = new EditText(MexRemoteActivity.this);
                pass = new EditText(MexRemoteActivity.this);

                layout = new LinearLayout(MexRemoteActivity.this);

                pass.setTransformationMethod(new PasswordTransformationMethod());

                layout.setOrientation(LinearLayout.VERTICAL);

                params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);

                layout.setLayoutParams(params);
                user.setLayoutParams(params);
                pass.setLayoutParams(params);

                label_username = new TextView(MexRemoteActivity.this);
                label_password = new TextView(MexRemoteActivity.this);

                label_username.setText("Username:");
                label_password.setText("Password:");

                layout.addView(label_username);
                layout.addView(user);
                layout.addView(label_password);
                layout.addView(pass);
                logindialog.setView(layout);

                logindialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.cancel();
                    }
                });

                logindialog.setPositiveButton("Login", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String uvalue = user.getText().toString().trim();
                        String pvalue = pass.getText().toString().trim();
                        view.setHttpAuthUsernamePassword(host, realm, uvalue, pvalue);

                        handler.proceed(uvalue, pvalue);
                    }
                });
                logindialog.show();
                /* End login dialog box */
            } else /* We didn't get a 401 */
            {
                handler.proceed(userpass[0], userpass[1]);
            }
        } /* End onReceivedHttpAuthRequest */
    }); /* End Override */

    /* Run mdns to check for service in a "runnable" (async) */
    handler.post(new Runnable() {
        public void run() {
            startMdns();
        }
    });

    dialog = ProgressDialog.show(MexRemoteActivity.this, "", "Searching...", true);

    /* Let's put something in the webview while we're waiting */
    String summary = "<html><head><style>body { background-color: #000000; color: #ffffff; }></style></head><body><p>Searching for the media explorer webservice</p><p>More infomation on <a href=\"http://media-explorer.github.com\" >Media Explorer's home page</a></p></body></html>";
    web_view.loadData(summary, "text/html", "utf-8");

}