How do I resolve the authentication message that keeps popping up in a webview?

送分小仙女□ 提交于 2019-11-28 06:38:27

问题


I have a webview with authentication, in which the authentication message keeps popping up for the webview fragment when called.The authentication popup is the fault code 410 (already signed in: sign in/cancel) message, How do I pass my cookies for the session id to be maintained? Any clues? thanks! P.S: Please explain programmatically with respect to my code wherever possible as it's hard to understand when you explain without code.

Here is my code for the given fragment:

  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:


Try this out and see if it works for you (from my existing code):

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

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


来源:https://stackoverflow.com/questions/19256509/how-do-i-resolve-the-authentication-message-that-keeps-popping-up-in-a-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!