如何在我的代码中修复密码/用户名验证?

时间:2013-08-22 13:54:59

标签: java android

我有一个应用程序,我使用我的用户名和密码登录,然后切换到包含webview的页面。 webview识别此用户名和密码并加载内容(通过共享偏好),但问题是,它仅加载ONCE,当我导航到我的应用程序的其他部分并返回时,它显示一个空白屏幕,最终加载页面不能在网页视图中显示出来。无论如何要解决这个问题,保持webview识别用户名并通过每次你导航到页面并加载内容。这是相同的代码: 包含webview的页面:

public class AnswersFragmentWebView extends Fragment implements  MainActivity.BackPressListener<Fragment>  {

    private static final String SYMBOL = "symbol";
    private static final String SYMBOL_TYPE = "symbol_type";
    public  static final String CONTAINER_ID = "container_id";
    public static final String TAG_QUOTES_FRAGMENT_WEBVIEW = "AnswersFragmentWebView";
    public static void removeInstance(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment == null) {
            return;
        }

        final FragmentStackManager stackManager = FragmentStackManager.getInstance();
        if (stackManager.getTopFragment() instanceof AnswersFragmentWebView) {
            stackManager.popTopFragment();
        }
    }

    private boolean goingBack = false;
    private boolean onBackPressClearStack = true;
    private WebView webView;
    private final static String URL = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=dark&uuid=PADACT-002&userAgent=iphone";
    //private final static String URL = "https://www.google.com";
    SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
    private final  String USERNAME =manager.getLoginUsername(); 
    private final  String PASSWORD = manager.getDecryptedLoginPassword();
    private final static String HOST = "https://amers1.mobile13.cp.justice.com/msf1.0/fwd/answers/answers/service/v1/?q=ibm%20revenue&ui.theme=novadark&uuid=PADACT-002&userAgent=iphone";
    private final static String REALM = "Users Only";

    public void setOnBackPressClearStack(boolean b){
        onBackPressClearStack = b;
    }
    public boolean webViewSteppedBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();

            return true;
        }
        return false;
    }

    @Override
    public boolean backPressed(final MainActivity mainActivity) {
        if (webViewSteppedBack()) {
            return true;
        }

        if (onBackPressClearStack) {
            goingBack = true;
            FragmentUtils.onBackPressedKnockFragsOffStack(mainActivity, this);
        }
        return false;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId, final int inAnimation, final int outAnimation, final int popInAnimation, final int popOutAnimation) {
        final Bundle bundle = new Bundle();
        bundle.putString(AnswersFragmentWebView.SYMBOL, searchAutoSuggestSymbol);
        bundle.putString(AnswersFragmentWebView.SYMBOL_TYPE, symbolType);
        bundle.putInt(AnswersFragmentWebView.CONTAINER_ID, containerViewId);
        fragment.setArguments(bundle);

        FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, containerViewId);
        fragmentInfo.setAnimation(inAnimation, outAnimation);
        fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);
        fragmentInfo.setFragmentTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.nav_option_quotes));
        FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);

        return fragment;
    }

    private static AnswersFragmentWebView __newInstance(final AnswersFragmentWebView fragment, final FragmentManager manager,
            final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId, R.anim.slide_in_from_right, R.anim.slide_out_to_left, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }


    private static void clearWebView(final FragmentManager manager) {
        final AnswersFragmentWebView fragment = (AnswersFragmentWebView) manager.findFragmentByTag(TAG_QUOTES_FRAGMENT_WEBVIEW);
        if (fragment != null && fragment instanceof AnswersFragmentWebView) {
            ((AnswersFragmentWebView)fragment).clearWebView();
        }
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container);
    }

    public static AnswersFragmentWebView newInstance(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType, int containerViewId) {
        clearWebView(manager);
        return __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final FragmentManager manager, final String searchAutoSuggestSymbol,  final String symbolType, int containerViewId) {
        AnswersFragmentWebView fragment =  __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, containerViewId);
        fragment.setOnBackPressClearStack(false);
        return fragment;
    }

    public static AnswersFragmentWebView newInstanceNoBackPressed(final AnswersFragmentWebView fragment, final FragmentManager manager, final String searchAutoSuggestSymbol, final String symbolType, int containerViewId) {
        fragment.setOnBackPressClearStack(false);
        return __newInstance(fragment, manager, searchAutoSuggestSymbol, symbolType, containerViewId);
    }

    public static AnswersFragmentWebView newInstanceForSearch(final FragmentManager manager, final String searchAutoSuggestSymbol, String symbolType) {
        AnswersFragmentWebView fragment = __newInstance(new AnswersFragmentWebView(), manager, searchAutoSuggestSymbol, symbolType, R.id.fragment_container, R.anim.no_animation, R.anim.slide_out_to_right, R.anim.slide_in_from_right, R.anim.slide_out_to_right);
        return fragment;
    }

    public void clearWebView() {
        if (webView != null) {
            webView.removeAllViews();
            webView.destroy();
            webView = null;
        }
    }



    @SuppressWarnings("deprecation")
    @SuppressLint("NewApi")
    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (goingBack) {
            return null;
        }
        final MainActivity activity = (MainActivity) getActivity();

        activity.setBackPressListener(this);


        final View view = inflater.inflate(R.layout.fragment_search_answers, container, false);

        if (!NetworkUtils.isOnline()) {
            LayoutUtils.showNoResult(view, R.id.quotes_webview_container);
            return view;

        }

        // setup webview
        webView = (WebView) view.findViewById(R.id.webview);


        webView.setVisibility(View.VISIBLE);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new WebChromeClient());
        webView.setBackgroundColor(0);
        webView.requestFocus();
        webView.reload();
        webView.getSettings().setSavePassword(true);
        webView.getSettings().setSaveFormData(true);
        webView.getSettings().getSaveFormData();
        webView.getSettings().getSavePassword();
        //WebViewDatabase.getInstance(getActivity()).clearHttpAuthUsernamePassword();
        WebViewDatabase.getInstance(getActivity()).hasHttpAuthUsernamePassword();
        webView.setHttpAuthUsernamePassword(HOST, REALM, USERNAME, PASSWORD);
        webView.setWebViewClient(new AnswersWebView(this,webView));
        webView.loadUrl(URL);



        return view;
    }

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getArguments().getString(AnswersFragmentWebView.SYMBOL);
    }


}

webview客户端:

public class AnswersWebView extends WebViewClient {

    private String loginCookie;
    private Context mContext;
    private WebView mWebView;

    public AnswersWebView(AnswersFragmentWebView answersFragmentWebView, WebView webview) {
        super();

        //mContext = answersFragmentWebView;
        mWebView = webview;
    }

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

    @Override
    public void onPageFinished( WebView view, String url ) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setCookie(url, loginCookie);
    }

    @Override
    public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
        Toast.makeText(view.getContext(), "ÉyÅ[ÉWì«Ç›çûÇ›ÉGÉâÅ[", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLoadResource( WebView view, String url ){
        CookieManager cookieManager = CookieManager.getInstance();
        loginCookie = cookieManager.getCookie(url);
    }

    @Override
    public boolean shouldOverrideUrlLoading( WebView view, String url ) {
        return false;
    }

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

    @Override
    public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){
        SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
        String userName = manager.getLoginUsername();
        String userPass = manager.getDecryptedLoginPassword();

        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);
        }
    }

    private void showHttpAuthDialog( final HttpAuthHandler handler, final String host, final String realm, final String title, final String name, final String password ) {
        LinearLayout llayout = new LinearLayout((Activity)mContext);
        final TextView textview1 = new TextView((Activity)mContext);
        final EditText edittext1 = new EditText((Activity)mContext);
        final TextView textview2 = new TextView((Activity)mContext);
        final EditText edittext2 = new EditText((Activity)mContext);
        llayout.setOrientation(LinearLayout.VERTICAL);
        textview1.setText("username:");
        textview2.setText("password:");
        llayout.addView(textview1);
        llayout.addView(edittext1);
        llayout.addView(textview2);
        llayout.addView(edittext2);

        final Builder mHttpAuthDialog = new AlertDialog.Builder((Activity)mContext);
        mHttpAuthDialog.setTitle("Basic Authentication")
        .setView(llayout)
        .setCancelable(false)
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                EditText etUserName = edittext1;
                String userName = etUserName.getText().toString();
                EditText etUserPass = edittext2;
                String userPass = etUserPass.getText().toString();

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

                handler.proceed(userName, userPass);
            }
        })
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                handler.cancel();
            }
        })
        .create().show();
    }

}

谢谢! 贾斯汀

4 个答案:

答案 0 :(得分:2)

确定。

您必须在onResume而不是OnCreate

中添加用户名/密码

就像本文档中的解释一样 http://developer.android.com/reference/android/app/Activity.html

答案 1 :(得分:1)

将SharedPref代码移至onClick并在此处报告...

答案 2 :(得分:1)

这是cookie管理的问题。

案例:~1 如果您正在访问其他网站(Facebook,Gmail等) 要解决这个问题,你必须维护通过vebView发布的cookie文件。

&安培;将其发送回下次新页面请求。

案例:~2 如果您访问自己的网站,那么另一个问题解决方案是您可以检查服务器端(在您的网站中)设备信息&amp;将它与登录时的设备信息进行比较。

或者您可以在隐藏标签中发送隐藏数据&amp;在您的应用中验证它。

答案 3 :(得分:1)

在我之前的项目中,我遇到了一些类似的问题。我用这种方法解决了这个问题 - 在 onCreate 中实现空白/默认布局,然后从sharedPref加载配置并在 onResume 中设置布局的参数值。在离开页面之前,在 onPause 中保存配置更改(如果发生)。如果这看起来不错,你可以在你的情况下检查它。