Example usage for android.webkit CookieManager getInstance

List of usage examples for android.webkit CookieManager getInstance

Introduction

In this page you can find the example usage for android.webkit CookieManager getInstance.

Prototype

public static CookieManager getInstance() 

Source Link

Document

Gets the singleton CookieManager instance.

Usage

From source file:org.zywx.wbpalmstar.platform.push.PushRecieveMsgReceiver.java

private Bitmap getIconBitmap(Context context, String iconUrl) {
    try {/* ww w  .  ja  v a  2  s  .  com*/
        URL uRL = new URL(iconUrl);
        HttpURLConnection connection = (HttpURLConnection) uRL.openConnection();
        String cookie = CookieManager.getInstance().getCookie(iconUrl);
        if (null != cookie) {
            connection.setRequestProperty(SM.COOKIE, cookie);
        }
        connection.connect();
        if (200 == connection.getResponseCode()) {
            InputStream input = connection.getInputStream();
            if (input != null) {
                Environment.getDownloadCacheDirectory();
                File ecd = context.getExternalCacheDir();
                File file = new File(ecd, "pushIcon.png");
                OutputStream outStream = new FileOutputStream(file);
                byte buf[] = new byte[8 * 1024];
                while (true) {
                    int numread = input.read(buf);
                    if (numread == -1) {
                        break;
                    }
                    outStream.write(buf, 0, numread);
                }
                Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                return bitmap;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.github.dfa.diaspora_android.activity.PodSelectionFragment.java

@Override
public void onPodSelectionDialogResult(DiasporaPod pod, boolean accepted) {
    System.out.println(accepted + ": " + pod.toString());
    if (accepted) {
        app.getSettings().setPod(pod);//ww  w  .  ja  v  a 2s. c  o m

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                CookieManager.getInstance().removeAllCookies(null);
                CookieManager.getInstance().removeSessionCookies(null);
            } else {
                //noinspection deprecation
                CookieManager.getInstance().removeAllCookie();
                //noinspection deprecation
                CookieManager.getInstance().removeSessionCookie();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        MainActivity mainActivity = (MainActivity) getActivity();
        DiasporaUrlHelper urlHelper = new DiasporaUrlHelper(appSettings);
        mainActivity.onPodSelectionDialogResult(pod, accepted);
        mainActivity.openDiasporaUrl(urlHelper.getSignInUrl());
    }
}

From source file:org.apache.cordova.filetransfer.FileTransfer.java

private String getCookies(final String target) {
    boolean gotCookie = false;
    String cookie = null;//  w  w  w.ja  v  a2 s  . c o  m
    Class webViewClass = webView.getClass();
    try {
        Method gcmMethod = webViewClass.getMethod("getCookieManager");
        Class iccmClass = gcmMethod.getReturnType();
        Method gcMethod = iccmClass.getMethod("getCookie", String.class);

        cookie = (String) gcMethod.invoke(iccmClass.cast(gcmMethod.invoke(webView)), target);

        gotCookie = true;
    } catch (NoSuchMethodException e) {
    } catch (IllegalAccessException e) {
    } catch (InvocationTargetException e) {
    } catch (ClassCastException e) {
    }

    if (!gotCookie) {
        cookie = CookieManager.getInstance().getCookie(target);
    }

    return cookie;
}

From source file:com.iStudy.Study.Renren.Util.java

public static void clearCookies(Context context) {
    @SuppressWarnings("unused")
    CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();/*from w w w . ja  v  a  2s  . com*/
}

From source file:android.webkit.LoadListener.java

/**
 * Parse the headers sent from the server.
 * @param headers gives up the HeaderGroup
 * IMPORTANT: as this is called from network thread, can't call native
 * directly/*  w ww. j  av  a  2  s  .c o  m*/
 */
public void headers(Headers headers) {
    if (Config.LOGV)
        Log.v(LOGTAG, "LoadListener.headers");
    if (mCancelled)
        return;
    mHeaders = headers;
    mMimeType = "";
    mEncoding = "";

    ArrayList<String> cookies = headers.getSetCookie();
    for (int i = 0; i < cookies.size(); ++i) {
        CookieManager.getInstance().setCookie(mUri, cookies.get(i));
    }

    long contentLength = headers.getContentLength();
    if (contentLength != Headers.NO_CONTENT_LENGTH) {
        mContentLength = contentLength;
    } else {
        mContentLength = 0;
    }

    String contentType = headers.getContentType();
    if (contentType != null) {
        parseContentTypeHeader(contentType);

        // If we have one of "generic" MIME types, try to deduce
        // the right MIME type from the file extension (if any):
        if (mMimeType.equalsIgnoreCase("text/plain")
                || mMimeType.equalsIgnoreCase("application/octet-stream")) {

            String newMimeType = guessMimeTypeFromExtension();
            if (newMimeType != null) {
                mMimeType = newMimeType;
            }
        } else if (mMimeType.equalsIgnoreCase("text/vnd.wap.wml")) {
            // As we don't support wml, render it as plain text
            mMimeType = "text/plain";
        } else {
            // XXX: Until the servers send us either correct xhtml or
            // text/html, treat application/xhtml+xml as text/html.
            // It seems that xhtml+xml and vnd.wap.xhtml+xml mime
            // subtypes are used interchangeably. So treat them the same.
            if (mMimeType.equalsIgnoreCase("application/xhtml+xml")
                    || mMimeType.equals("application/vnd.wap.xhtml+xml")) {
                mMimeType = "text/html";
            }
        }
    } else {
        /* Often when servers respond with 304 Not Modified or a
           Redirect, then they don't specify a MIMEType. When this
           occurs, the function below is called.  In the case of
           304 Not Modified, the cached headers are used rather
           than the headers that are returned from the server. */
        guessMimeType();
    }

    // is it an authentication request?
    boolean mustAuthenticate = (mStatusCode == HTTP_AUTH || mStatusCode == HTTP_PROXY_AUTH);
    // is it a proxy authentication request?
    boolean isProxyAuthRequest = (mStatusCode == HTTP_PROXY_AUTH);
    // is this authentication request due to a failed attempt to
    // authenticate ealier?
    mAuthFailed = false;

    // if we tried to authenticate ourselves last time
    if (mAuthHeader != null) {
        // we failed, if we must to authenticate again now and
        // we have a proxy-ness match
        mAuthFailed = (mustAuthenticate && isProxyAuthRequest == mAuthHeader.isProxy());

        // if we did NOT fail and last authentication request was a
        // proxy-authentication request
        if (!mAuthFailed && mAuthHeader.isProxy()) {
            Network network = Network.getInstance(mContext);
            // if we have a valid proxy set
            if (network.isValidProxySet()) {
                /* The proxy credentials can be read in the WebCore thread
                */
                synchronized (network) {
                    // save authentication credentials for pre-emptive proxy
                    // authentication
                    network.setProxyUsername(mAuthHeader.getUsername());
                    network.setProxyPassword(mAuthHeader.getPassword());
                }
            }
        }
    }
    // it is only here that we can reset the last mAuthHeader object
    // (if existed) and start a new one!!!
    mAuthHeader = null;
    if (mustAuthenticate) {
        if (mStatusCode == HTTP_AUTH) {
            mAuthHeader = parseAuthHeader(headers.getWwwAuthenticate());
        } else {
            mAuthHeader = parseAuthHeader(headers.getProxyAuthenticate());
            // if successfully parsed the header
            if (mAuthHeader != null) {
                // mark the auth-header object as a proxy
                mAuthHeader.setProxy();
            }
        }
    }

    // Only create a cache file if the server has responded positively.
    if ((mStatusCode == HTTP_OK || mStatusCode == HTTP_FOUND || mStatusCode == HTTP_MOVED_PERMANENTLY
            || mStatusCode == HTTP_TEMPORARY_REDIRECT) && mNativeLoader != 0) {
        // Content arriving from a StreamLoader (eg File, Cache or Data)
        // will not be cached as they have the header:
        // cache-control: no-store
        mCacheResult = CacheManager.createCacheFile(mUrl, mStatusCode, headers, mMimeType, false);
        if (mCacheResult != null) {
            mCacheResult.encoding = mEncoding;
        }
    }
    sendMessageInternal(obtainMessage(MSG_CONTENT_HEADERS));
}

From source file:com.microsoft.aad.adal.hello.MainActivity.java

public void onClickClearCookies(View view) {
    CookieSyncManager.createInstance(MainActivity.this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();/*ww  w . j av a2  s  .  c  o  m*/
    CookieSyncManager.getInstance().sync();
}

From source file:com.phonegap.FileTransfer.java

/**
 * Uploads the specified file to the server URL provided using an HTTP 
 * multipart request. //from  ww w  .j a va 2 s . co  m
 * @param file      Full path of the file on the file system
 * @param server        URL of the server to receive the file
 * @param fileKey       Name of file request parameter
 * @param fileName      File name to be used on server
 * @param mimeType      Describes file content type
 * @param params        key:value pairs of user-defined parameters
 * @return FileUploadResult containing result of upload request
 */
public FileUploadResult upload(String file, String server, final String fileKey, final String fileName,
        final String mimeType, JSONObject params, boolean trustEveryone) throws IOException, SSLException {
    // Create return object
    FileUploadResult result = new FileUploadResult();

    // Get a input stream of the file on the phone
    InputStream fileInputStream = getPathFromUri(file);

    HttpURLConnection conn = null;
    DataOutputStream dos = null;

    int bytesRead, bytesAvailable, bufferSize;
    long totalBytes;
    byte[] buffer;
    int maxBufferSize = 8096;

    //------------------ CLIENT REQUEST
    // open a URL connection to the server 
    URL url = new URL(server);

    // Open a HTTP connection to the URL based on protocol 
    if (url.getProtocol().toLowerCase().equals("https")) {
        // Using standard HTTPS connection. Will not allow self signed certificate
        if (!trustEveryone) {
            conn = (HttpsURLConnection) url.openConnection();
        }
        // Use our HTTPS connection that blindly trusts everyone.
        // This should only be used in debug environments
        else {
            // Setup the HTTPS connection class to trust everyone
            trustAllHosts();
            HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
            // Save the current hostnameVerifier
            defaultHostnameVerifier = https.getHostnameVerifier();
            // Setup the connection not to verify hostnames 
            https.setHostnameVerifier(DO_NOT_VERIFY);
            conn = https;
        }
    }
    // Return a standard HTTP conneciton
    else {
        conn = (HttpURLConnection) url.openConnection();
    }

    // Allow Inputs
    conn.setDoInput(true);

    // Allow Outputs
    conn.setDoOutput(true);

    // Don't use a cached copy.
    conn.setUseCaches(false);

    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDRY);

    // Set the cookies on the response
    String cookie = CookieManager.getInstance().getCookie(server);
    if (cookie != null) {
        conn.setRequestProperty("Cookie", cookie);
    }

    dos = new DataOutputStream(conn.getOutputStream());

    // Send any extra parameters
    try {
        for (Iterator iter = params.keys(); iter.hasNext();) {
            Object key = iter.next();
            dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
            dos.writeBytes("Content-Disposition: form-data; name=\"" + key.toString() + "\"; ");
            dos.writeBytes(LINE_END + LINE_END);
            dos.writeBytes(params.getString(key.toString()));
            dos.writeBytes(LINE_END);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    dos.writeBytes(LINE_START + BOUNDRY + LINE_END);
    dos.writeBytes("Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\"" + fileName
            + "\"" + LINE_END);
    dos.writeBytes("Content-Type: " + mimeType + LINE_END);
    dos.writeBytes(LINE_END);

    // create a buffer of maximum size
    bytesAvailable = fileInputStream.available();
    bufferSize = Math.min(bytesAvailable, maxBufferSize);
    buffer = new byte[bufferSize];

    // read file and write it into form...
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    totalBytes = 0;

    while (bytesRead > 0) {
        totalBytes += bytesRead;
        result.setBytesSent(totalBytes);
        dos.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    // send multipart form data necesssary after file data...
    dos.writeBytes(LINE_END);
    dos.writeBytes(LINE_START + BOUNDRY + LINE_START + LINE_END);

    // close streams
    fileInputStream.close();
    dos.flush();
    dos.close();

    //------------------ read the SERVER RESPONSE
    StringBuffer responseString = new StringBuffer("");
    DataInputStream inStream = new DataInputStream(conn.getInputStream());
    String line;
    while ((line = inStream.readLine()) != null) {
        responseString.append(line);
    }
    Log.d(LOG_TAG, "got response from server");
    Log.d(LOG_TAG, responseString.toString());

    // send request and retrieve response
    result.setResponseCode(conn.getResponseCode());
    result.setResponse(responseString.toString());

    inStream.close();
    conn.disconnect();

    // Revert back to the proper verifier and socket factories
    if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) {
        ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier);
        HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory);
    }

    return result;
}

From source file:org.microg.gms.auth.login.LoginActivity.java

private void closeWeb(boolean programmaticAuth) {
    setMessage(R.string.auth_finalize);/*from  w w  w .j  a v a 2 s . co  m*/
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            webView.setVisibility(INVISIBLE);
        }
    });
    String cookies = CookieManager.getInstance()
            .getCookie(programmaticAuth ? PROGRAMMATIC_AUTH_URL : EMBEDDED_SETUP_URL);
    String[] temp = cookies.split(";");
    for (String ar1 : temp) {
        if (ar1.trim().startsWith(COOKIE_OAUTH_TOKEN + "=")) {
            String[] temp1 = ar1.split("=");
            retrieveRtToken(temp1[1]);
            return;
        }
    }
    showError(R.string.auth_general_error_desc);
}

From source file:com.wellsandwhistles.android.redditsp.fragments.WebViewFragment.java

@Override
public void onDestroyView() {

    webView.stopLoading();/*from  w  ww . j a  v a  2  s.c  o  m*/
    webView.loadData("<html></html>", "text/plain", "UTF-8");
    webView.reload();
    webView.loadUrl("about:blank");
    outer.removeAllViews();
    webView.destroy();

    final CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();

    super.onDestroyView();
}

From source file:de.baumann.browser.Browser.java

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

    WebView.enableSlowWholeDocumentDraw();
    setContentView(R.layout.activity_browser);
    helper_main.onStart(Browser.this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/* w w w . j  a  v a 2  s  .co  m*/

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    PreferenceManager.setDefaultValues(this, R.xml.user_settings_search, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    sharedPref.edit().putInt("keyboard", 0).apply();
    sharedPref.getInt("keyboard", 0);

    customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

    editText = (EditText) findViewById(R.id.editText);
    editText.setHint(R.string.app_search_hint);
    editText.clearFocus();

    imageButton = (ImageButton) findViewById(R.id.imageButton);
    imageButton.setVisibility(View.INVISIBLE);
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mWebView.scrollTo(0, 0);
            imageButton.setVisibility(View.INVISIBLE);
            actionBar = getSupportActionBar();
            assert actionBar != null;
            if (!actionBar.isShowing()) {
                editText.setText(mWebView.getTitle());
                actionBar.show();
            }
            setNavArrows();
        }
    });

    SwipeRefreshLayout swipeView = (SwipeRefreshLayout) findViewById(R.id.swipe);
    assert swipeView != null;
    swipeView.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent);
    swipeView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
        }
    });

    mWebView = (ObservableWebView) findViewById(R.id.webView);
    if (sharedPref.getString("fullscreen", "2").equals("2")
            || sharedPref.getString("fullscreen", "2").equals("3")) {
        mWebView.setScrollViewCallbacks(this);
    }

    mWebChromeClient = new myWebChromeClient();
    mWebView.setWebChromeClient(mWebChromeClient);

    imageButton_left = (ImageButton) findViewById(R.id.imageButton_left);
    imageButton_right = (ImageButton) findViewById(R.id.imageButton_right);

    if (sharedPref.getBoolean("arrow", false)) {
        imageButton_left.setVisibility(View.VISIBLE);
        imageButton_right.setVisibility(View.VISIBLE);
    } else {
        imageButton_left.setVisibility(View.INVISIBLE);
        imageButton_right.setVisibility(View.INVISIBLE);
    }

    helper_webView.webView_Settings(Browser.this, mWebView);
    helper_webView.webView_WebViewClient(Browser.this, swipeView, mWebView, editText);

    mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);

    if (isNetworkUnAvailable()) {
        if (sharedPref.getBoolean("offline", false)) {
            if (isNetworkUnAvailable()) { // loading offline
                mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
                Snackbar.make(mWebView, R.string.toast_cache, Snackbar.LENGTH_SHORT).show();
            }
        } else {
            Snackbar.make(mWebView, R.string.toast_noInternet, Snackbar.LENGTH_SHORT).show();
        }
    }

    mWebView.setDownloadListener(new DownloadListener() {

        public void onDownloadStart(final String url, String userAgent, final String contentDisposition,
                final String mimetype, long contentLength) {

            registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

            final String filename = URLUtil.guessFileName(url, contentDisposition, mimetype);
            Snackbar snackbar = Snackbar
                    .make(mWebView, getString(R.string.toast_download_1) + " " + filename, Snackbar.LENGTH_LONG)
                    .setAction(getString(R.string.toast_yes), new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                            request.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url));
                            request.allowScanningByMediaScanner();
                            request.setNotificationVisibility(
                                    DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                                    filename);
                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                            dm.enqueue(request);

                            Snackbar.make(mWebView, getString(R.string.toast_download) + " " + filename,
                                    Snackbar.LENGTH_SHORT).show();
                        }
                    });
            snackbar.show();
        }
    });

    helper_editText.editText_Touch(editText, Browser.this, mWebView);
    helper_editText.editText_EditorAction(editText, Browser.this, mWebView);
    helper_editText.editText_FocusChange(editText, Browser.this);

    onNewIntent(getIntent());
    helper_main.grantPermissionsStorage(Browser.this);
}