Android。Webview。Basic認証

Basic認証

//basic 認証
private class MyWebClient extends WebViewClient {
            @Override
            public void onReceivedHttpAuthRequest(WebView view,
                                                  final HttpAuthHandler handler, final String host, final String realm) {

                String userName = null;
                String userPass = null;

                if (handler.useHttpAuthUsernamePassword() && view != null) {
                    String[] haup = view.getHttpAuthUsernamePassword(host, realm);
                    if (haup != null && haup.length == 2) {
                        userName = haup[0];
                        userPass = haup[1];
                    }
                }

                if (userName != null && userPass != null) {
                    handler.proceed(userName, userPass);
                } else {
                    showHttpAuthDialog(handler, host, realm, null, null, null);

                    // If you hope for the state that the username/password is input.
                    //showHttpAuth(handler, host, realm, null, "username", "password");
                }
            }
}

private void showHttpAuthDialog(final HttpAuthHandler handler,
                                    final String host, final String realm, final String title,
                                    final String name, final String password) {

        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(
                R.layout.basicauth_entry, null);

        // username/passwordを受け取った場合はダイアログに入力する処理とか

        final AlertDialog.Builder[] mHttpAuthDialog = new AlertDialog.Builder[1];

        mHttpAuthDialog[0] = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
        mHttpAuthDialog[0].setTitle("Enter the password")
                .setView(textEntryView)
                .setCancelable(false);
        mHttpAuthDialog[0].setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText etUserName = (EditText) textEntryView.findViewById(R.id.username_edit);
                String userName = etUserName.getText().toString();
                EditText etUserPass = (EditText) textEntryView.findViewById(R.id.password_edit);
                String userPass = etUserPass.getText().toString();

                myWebview.setHttpAuthUsernamePassword(host, realm, name, password);

                handler.proceed(userName, userPass);
                mHttpAuthDialog[0] = null;
            }
        });
        mHttpAuthDialog[0].setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                handler.cancel();
                mHttpAuthDialog[0] = null;
            }
        });

        mHttpAuthDialog[0].create().show();
    }