如何解决在Webview中不断弹出的身份验证消息?

时间:2013-10-08 19:24:32

标签: android android-fragments android-webview android-fragmentactivity android-authenticator

我有一个带有身份验证的webview,其中身份验证消息在调用时不断弹出webview片段。身份验证弹出窗口是故障代码410(已登录:登录/取消)消息,如何通过我的会话ID的cookie要维护吗?有线索吗?谢谢! P.S:请尽可能以编程方式解释我的代码,因为在没有代码的情况下进行解释时很难理解。

这是给定片段的代码:

  public class WebViewFragment extends Fragment implements OnClickListener , MainActivity.BackPressListener<Fragment> {

        private static final String SEARCH_TERM = "search_term";
        private static String mSearchTerm;
        private WebView mWebview;
        private static WebViewFragment sUserProfileManager;



        public  final static String SYMBOL = "symbol";

        public static int PIC_WIDTH = 30;
        private static final String SYMBOL_TYPE = "symbol_type";
        public  static final String CONTAINER_ID = "container_id";
        public static final String TAG_FRAGMENT_WEBVIEW = "WebViewFragment";
        SharedPreferencesManager manager = SharedPreferencesManager.getInstance();
        private static  String URL;
        private final  String USERNAME = manager.getLoginUsername();
        private final  String PASSWORD = manager.getDecryptedLoginPassword();

        LinearLayout progressBar;
        private static WebViewFragment __newInstance(final WebViewFragment fragment, final FragmentManager manager,
                final String searchTerm, final String symbolType, int containerViewId, final int inAnimation, final int outAnimation, final int popInAnimation, final int popOutAnimation) {

            final Bundle bundle = new Bundle();
            bundle.putString(SEARCH_TERM, searchTerm);
            bundle.putString(WebViewFragment.SYMBOL_TYPE, symbolType);
            bundle.putInt(WebViewFragment.CONTAINER_ID, containerViewId);
            fragment.setArguments(bundle);

            FragmentInfo fragmentInfo = new FragmentInfo(TransactionMethods.ADD, containerViewId);
            fragmentInfo.setAnimation(inAnimation, outAnimation);
            fragmentInfo.setPopAnimation(popInAnimation, popOutAnimation);

            fragmentInfo.setFragmentTag(TAG_FRAGMENT_WEBVIEW);
            fragmentInfo.setActionBarTitle(Application.getAppResources().getString(R.string.title_search));
            FragmentStackManager.getInstance().transitionFragment(manager, fragment, fragmentInfo);
            URL = getUrl();
            return fragment;
        }

         @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                Bundle bundle = this.getArguments();
                URL = getUrl();

                if(bundle != null)
                    mSearchTerm = getArguments().getString(SEARCH_TERM);

                 }
         public void setSearchTerms(String sTerms){
             mSearchTerm = sTerms;
         }
        public static void removeInstance(final FragmentManager manager) {
            final WebViewFragment fragment = (WebViewFragment) manager.findFragmentByTag(TAG_FRAGMENT_WEBVIEW);
            if (fragment == null) {
                return;
            }

            final FragmentStackManager stackManager = FragmentStackManager.getInstance();
            if (stackManager.getTopFragment() instanceof WebViewFragment) {
                stackManager.popTopFragment();
            }
        }
        private boolean goingBack = false;
        private boolean onBackPressClearStack = true;

        public void setOnBackPressClearStack(boolean b){
            onBackPressClearStack = b;
        }


        public boolean webViewSteppedBack() {
            if (mWebview != null && mWebview.canGoBack()) {
                  final Animation slide =  new TranslateAnimation(100, 1000, 0, 0);
                    slide.setDuration(800);


                    mWebview.startAnimation(slide);
                WebBackForwardList mWebBackForwardList = mWebview.copyBackForwardList();
                String historyUrl = mWebBackForwardList.getItemAtIndex(mWebBackForwardList.getCurrentIndex()-1).getUrl();
                mWebview.goBack();

                return true;
            }
            return false;
        }


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

            if (onBackPressClearStack) {
                goingBack = true;
            }
            return false;
        }
        private static String getUrl(){
            String url = "";

            final String getuuid = SharedPreferencesManager.getInstance().getUUID();
            final String environmentApi = SharedPreferencesManager.getInstance().getEnvironmentApi();
            if (environmentApi.equalsIgnoreCase(NetworkUtils.Apis.ALPHA)) {

                    url = "https://cp.com/fwd/service/v1/?q="+mSearchTerm+"%20revenue&ui.theme=novadark&uuid="+getuuid+"&userAgent=android";



            } 

             return url;
        }


        private static WebViewFragment __newInstance(final WebViewFragment fragment, final FragmentManager manager,
                final String searchTerm, final String symbolType, int containerViewId) {

            return __newInstance(fragment, manager,searchTerm, 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 WebViewFragment fragment = (WebViewFragment) manager.findFragmentByTag(TAG_FRAGMENT_WEBVIEW);
            if (fragment != null && fragment instanceof WebViewFragment) {
                ((WebViewFragment)fragment).clearWebView();
            }
        }

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

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

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

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

        public static WebViewFragment newInstanceForSearch(final FragmentManager manager, final String searchTerm, String symbolType) {
            WebViewFragment fragment = __newInstance(new WebViewFragment(), manager, searchTerm, 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;
        }

        @Override
        public void onResume() {
            super.onResume();
            final MainActivity activity = (MainActivity) getActivity();
            activity.updateActionBarTitle();
            activity.setBackPressListener(this);

            }
        public void clearWebView() {
            if (mWebview != null) {
                mWebview.removeAllViews();
                mWebview.destroy();
                mWebview = null;
            }
        }
        @Override
        public void onClick(View v) {

          getActivity().finish();
        }

        @SuppressWarnings("deprecation")
        @SuppressLint({
                "SetJavaScriptEnabled", "NewApi"
        })
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            if (goingBack) {
                return null;
            }
            final MainActivity activity = (MainActivity) getActivity();

            activity.setBackPressListener(this);
            View view = inflater.inflate(R.layout.fragment_search, container, false);


            mWebview =  (WebView)view.findViewById(R.id.webview);
            progressBar = (LinearLayout) view.findViewById(R.id.loading);   
            mWebview.setVisibility(View.VISIBLE);

            progressBar.setVisibility(View.VISIBLE);

                mWebview.setWebViewClient(new MyWebViewClient(this, mWebview));
                mWebview.getSettings().setUseWideViewPort(true);

                mWebview.setBackgroundColor(0);
                mWebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                mWebview.getSettings().setAllowFileAccess(true);
                mWebview.getSettings().setDomStorageEnabled(true);
                mWebview.getSettings().setJavaScriptEnabled(true);

                mWebview.setScrollbarFadingEnabled(false);
                mWebview.getSettings().getLoadsImagesAutomatically();

                    android.webkit.CookieManager webCookieManager =
                        CookieManager.getInstance();
                    webCookieManager.setAcceptCookie(true);


                mWebview.setWebChromeClient(new WebChromeClient() {
                       @Override
                       public void onReceivedTitle(WebView view, String title) {
                          super.onReceivedTitle(view, title);

                          String serverError = "412";
                          if (title.contains(serverError)) {
                              view.stopLoading();
                              SearchResultsFragment.newInstance(getFragmentManager(), mSearchTerm);
                          }
                       }
                    });
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    mWebview.getSettings().setDisplayZoomControls(false);
                SharedPreferencesManager mgr = SharedPreferencesManager.getInstance();
                CookieStore cookieStore = mgr.getCookieStore();
                Cookie cookie = cookieStore.getCookies().get(0);
                String cookieString =  cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
                CookieManager cookieMgr = CookieManager.getInstance();
                cookieMgr.setCookie(URL, cookieString);



                mWebview.loadUrl(URL);


            return view;
        }


        public class MyWebViewClient extends WebViewClient {


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

            }

            @Override
            public void onPageFinished(WebView view, String url) {

                final Animation fade = new AlphaAnimation(0.0f, 1.0f);
                fade.setDuration(200);
                view.startAnimation(fade);

                view.setVisibility(View.VISIBLE);

                progressBar.setVisibility(View.GONE);

            }


            @Override
            public void onReceivedError( WebView view, int errorCode, String description, String failingUrl ) {
                Toast.makeText(view.getContext(), "Authentication Error", Toast.LENGTH_LONG).show();

                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            @Override
            public void onLoadResource( WebView view, String url ){

            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                    return super.shouldOverrideUrlLoading(view, url);

            }

            @Override
            public void onReceivedHttpAuthRequest( WebView view, final HttpAuthHandler handler, final String host, final String realm ){

                    handler.proceed(USERNAME,PASSWORD);

        }


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


    }

1 个答案:

答案 0 :(得分:0)

尝试一下,看看它是否适合你(来自我现有的代码):

public void onResume() {
    super.onResume();
    CookieSyncManager.getInstance().startSync();
}

public void onPause() {
    super.onPause();
    CookieSyncManager.getInstance().stopSync();
}