List of usage examples for android.webkit CookieManager getInstance
public static CookieManager getInstance()
From source file:org.zywx.wbpalmstar.engine.EDownloadDialog.java
private final String getCookie(String inUrl) { return CookieManager.getInstance().getCookie(inUrl); }
From source file:org.skt.runtime.html5apis.file.FileTransfer.java
/** * Uploads the specified file to the server URL provided using an HTTP multipart request. * @param source Full path of the file on the file system * @param target URL of the server to receive the file * @param args JSON Array of args * * args[2] fileKey Name of file request parameter * args[3] fileName File name to be used on server * args[4] mimeType Describes file content type * args[5] params key:value pairs of user-defined parameters * @return FileUploadResult containing result of upload request *///www .ja v a 2 s. c o m private PluginResult upload(String source, String target, JSONArray args) { Log.d(LOG_TAG, "upload " + source + " to " + target); HttpURLConnection conn = null; try { // Setup the options String fileKey = getArgument(args, 2, "file"); String fileName = getArgument(args, 3, "image.jpg"); String mimeType = getArgument(args, 4, "image/jpeg"); JSONObject params = args.optJSONObject(5); if (params == null) { params = new JSONObject(); } boolean trustEveryone = args.optBoolean(6); boolean chunkedMode = args.optBoolean(7) || args.isNull(7); //Always use chunked mode unless set to false as per API Log.d(LOG_TAG, "fileKey: " + fileKey); Log.d(LOG_TAG, "fileName: " + fileName); Log.d(LOG_TAG, "mimeType: " + mimeType); Log.d(LOG_TAG, "params: " + params); Log.d(LOG_TAG, "trustEveryone: " + trustEveryone); Log.d(LOG_TAG, "chunkedMode: " + chunkedMode); // Create return object FileUploadResult result = new FileUploadResult(); // Get a input stream of the file on the phone FileInputStream fileInputStream = (FileInputStream) getPathFromUri(source); 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(target); // 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 connection 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=" + BOUNDARY); // Handle the other headers try { JSONObject headers = params.getJSONObject("headers"); for (Iterator iter = headers.keys(); iter.hasNext();) { String headerKey = iter.next().toString(); conn.setRequestProperty(headerKey, headers.getString(headerKey)); } } catch (JSONException e1) { // No headers to be manipulated! } // Set the cookies on the response String cookie = CookieManager.getInstance().getCookie(target); if (cookie != null) { conn.setRequestProperty("Cookie", cookie); } /* * Store the non-file portions of the multipart data as a string, so that we can add it * to the contentSize, since it is part of the body of the HTTP request. */ String extraParams = ""; try { for (Iterator iter = params.keys(); iter.hasNext();) { Object key = iter.next(); if (!String.valueOf(key).equals("headers")) { extraParams += LINE_START + BOUNDARY + LINE_END; extraParams += "Content-Disposition: form-data; name=\"" + key.toString() + "\";"; extraParams += LINE_END + LINE_END; extraParams += params.getString(key.toString()); extraParams += LINE_END; } } } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); } extraParams += LINE_START + BOUNDARY + LINE_END; extraParams += "Content-Disposition: form-data; name=\"" + fileKey + "\";" + " filename=\""; String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END; String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END; // Should set this up as an option if (chunkedMode) { conn.setChunkedStreamingMode(maxBufferSize); } else { int stringLength = extraParams.getBytes("UTF-8").length + midParams.getBytes("UTF-8").length + tailParams.getBytes("UTF-8").length + fileName.getBytes("UTF-8").length; Log.d(LOG_TAG, "String Length: " + stringLength); int fixedLength = (int) fileInputStream.getChannel().size() + stringLength; Log.d(LOG_TAG, "Content Length: " + fixedLength); conn.setFixedLengthStreamingMode(fixedLength); } dos = new DataOutputStream(conn.getOutputStream()); dos.write(extraParams.getBytes("UTF-8")); //We don't want to chagne encoding, we just want this to write for all Unicode. dos.write(fileName.getBytes("UTF-8")); dos.write(midParams.getBytes("UTF-8")); // 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.write(tailParams.getBytes("UTF-8")); // close streams fileInputStream.close(); dos.flush(); dos.close(); //------------------ read the SERVER RESPONSE StringBuffer responseString = new StringBuffer(""); DataInputStream inStream; try { inStream = new DataInputStream(conn.getInputStream()); } catch (FileNotFoundException e) { Log.e(LOG_TAG, e.toString(), e); throw new IOException("Received error from server"); } 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(); // Revert back to the proper verifier and socket factories if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) conn).setHostnameVerifier(defaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(defaultSSLSocketFactory); } Log.d(LOG_TAG, "****** About to return a result from upload"); return new PluginResult(PluginResult.Status.OK, result.toJSONObject()); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (MalformedURLException e) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.e(LOG_TAG, error.toString(), e); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); return new PluginResult(PluginResult.Status.JSON_EXCEPTION); } catch (Throwable t) { // Shouldn't happen, but will JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); Log.wtf(LOG_TAG, error.toString(), t); return new PluginResult(PluginResult.Status.IO_EXCEPTION, error); } finally { if (conn != null) { conn.disconnect(); } } }
From source file:com.msdpe.authenticationdemo.AuthService.java
/** * Handles logging the user out including: * -deleting cookies so their login with a provider won't be cached in the web view * -removing the userdata from the shared preferences * -setting the current user object on the client to logged out * -optionally redirects to the login page if requested * @param shouldRedirectToLogin// www . j a va2 s. c o m */ public void logout(boolean shouldRedirectToLogin) { //Clear the cookies so they won't auto login to a provider again CookieSyncManager.createInstance(mContext); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); //Clear the user id and token from the shared preferences SharedPreferences settings = mContext.getSharedPreferences("UserData", 0); SharedPreferences.Editor preferencesEditor = settings.edit(); preferencesEditor.clear(); preferencesEditor.commit(); //Clear the user and return to the auth activity mClient.logout(); //Take the user back to the auth activity to relogin if requested if (shouldRedirectToLogin) { Intent logoutIntent = new Intent(mContext, AuthenticationActivity.class); logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(logoutIntent); } }
From source file:com.awadev.itslearningautologin.MainActivity.java
private void initUI() { // Navigation drawer mTitle = mDrawerTitle = getTitle();// w w w . ja v a 2 s .c o m String[] mPlanetTitles = getResources().getStringArray(R.array.planets_array); mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); mDrawerList = (ListView) findViewById(R.id.left_drawer); // set a custom shadow that overlays the main content when the drawer opens //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); // set up the drawer's list view with items and click listener mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mPlanetTitles)); mDrawerList.setOnItemClickListener(new DrawerItemClickListener()); // enable ActionBar app icon to behave as action to toggle nav drawer getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "close drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(mDrawerTitle); supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() } }; mDrawerLayout.setDrawerListener(mDrawerToggle); // End navigation drawer webViewPlaceholder = ((RelativeLayout) findViewById(R.id.webViewPlaceholder)); if (mWebView == null) { // Set cookies mWebView = new WebView(this); mWebView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); CookieSyncManager.createInstance(this); WebComponent.copyCookies(CookieManager.getInstance()); // Make the WebView behave like we want mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setDomStorageEnabled(true); mWebView.getSettings().setSupportZoom(true); mWebView.getSettings().setSupportMultipleWindows(true); mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS); mWebView.getSettings().setUserAgentString("itsLearning login - Android"); mWebView.setWebViewClient(new CustomWebClient()); // Load! String url = ((MainApplication) getApplication()).getLoadUrl(); if (url != null) { mWebView.loadUrl(url); ((MainApplication) getApplication()).setLoadUrl(null); } else mWebView.loadUrl(((MainApplication) getApplication()).baseURL + "/DashboardMenu.aspx"); } // Attach the WebView to its placeholder webViewPlaceholder.addView(mWebView); }
From source file:com.microsoft.firstapp.AuthService.java
/** * Handles logging the user out including: -deleting cookies so their login * with a provider won't be cached in the web view -removing the userdata * from the shared preferences -setting the current user object on the * client to logged out -optionally redirects to the login page if requested * /*from w w w. java 2 s . c om*/ * @param shouldRedirectToLogin */ public void logout(boolean shouldRedirectToLogin) { // Clear the cookies so they won't auto login to a provider again CookieSyncManager.createInstance(mContext); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); // Clear the user id and token from the shared preferences SharedPreferences settings = mContext.getSharedPreferences("UserData", 0); SharedPreferences.Editor preferencesEditor = settings.edit(); preferencesEditor.clear(); preferencesEditor.commit(); // Clear the user and return to the auth activity mClient.logout(); // Take the user back to the auth activity to relogin if requested if (shouldRedirectToLogin) { Intent logoutIntent = new Intent(mContext, LogInActivity.class); logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(logoutIntent); } }
From source file:com.microsoft.aad.adal.hello.MainActivity.java
private void clearSessionCookie() { // Webview by default does not clear session cookies even after app is // closed(Bug in Webview). // Example to clean session cookie Logger.v(TAG, "Clear session cookies"); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeSessionCookie(); CookieSyncManager.getInstance().sync(); }
From source file:com.nbplus.hybrid.BasicWebViewClient.java
/** * ??.//from w w w. j a v a 2s . c om * @param activity : context * @param view : ?? */ public BasicWebViewClient(Activity activity, WebView view, String alertTitleString, String confirmTitleString) { mWebView = view; mContext = activity; // This will handle downloading. It requires Gingerbread, though mDownloadManager = (DownloadManager) mContext.getSystemService(mContext.DOWNLOAD_SERVICE); mWebChromeClient = new BroadcastWebChromeClient(); // Enable remote debugging via chrome://inspect if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.setWebContentsDebuggingEnabled(true); } mWebView.setWebChromeClient(mWebChromeClient); WebSettings webSettings = mWebView.getSettings(); webSettings.setGeolocationEnabled(true); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); webSettings.setJavaScriptEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setDatabaseEnabled(true); // Use WideViewport and Zoom out if there is no viewport defined webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { webSettings.setMediaPlaybackRequiresUserGesture(false); } // Enable pinch to zoom without the zoom buttons webSettings.setBuiltInZoomControls(true); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) { // Hide the zoom controls for HONEYCOMB+ webSettings.setDisplayZoomControls(false); } webSettings.setAppCacheEnabled(true); mWebView.clearCache(true); webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Sets whether the WebView should allow third party cookies to be set. // Allowing third party cookies is a per WebView policy and can be set differently on different WebView instances. // Apps that target KITKAT or below default to allowing third party cookies. // Apps targeting LOLLIPOP or later default to disallowing third party cookies. CookieManager cookieManager = CookieManager.getInstance(); cookieManager.setAcceptCookie(true); cookieManager.setAcceptThirdPartyCookies(mWebView, true); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { mWebView.getSettings().setTextZoom(100); } if (StringUtils.isEmptyString(alertTitleString)) { mAlertTitleString = activity.getString(R.string.default_webview_alert_title); } else { mAlertTitleString = alertTitleString; } if (StringUtils.isEmptyString(confirmTitleString)) { mConfirmTitleString = activity.getString(R.string.default_webview_confirm_title); } else { mConfirmTitleString = confirmTitleString; } mWebView.setDownloadListener(new DownloadListener() { public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); mContext.startActivity(intent); } }); Log.d(TAG, ">> user agent = " + mWebView.getSettings().getUserAgentString()); }
From source file:com.acrutiapps.browser.ui.components.CustomWebView.java
@Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { DownloadItem item = new DownloadItem(url); item.addRequestHeader("Cookie", CookieManager.getInstance().getCookie(url)); String fileName = item.getFileName(); BasicHeader header = new BasicHeader("Content-Disposition", contentDisposition); HeaderElement[] helelms = header.getElements(); if (helelms.length > 0) { HeaderElement helem = helelms[0]; if (helem.getName().equalsIgnoreCase("attachment")) { NameValuePair nmv = helem.getParameterByName("filename"); if (nmv != null) { fileName = nmv.getValue(); }/*from ww w.j ava 2 s .c o m*/ } } item.setFilename(fileName); item.setIncognito(isPrivateBrowsingEnabled()); DownloadConfirmDialog dialog = new DownloadConfirmDialog(getContext()).setDownloadItem(item) .setCallbackListener(this); dialog.show(); }
From source file:com.eTilbudsavis.etasdk.SessionManager.java
private void postSession(final Listener<JSONObject> l) { Map<String, Object> args = new HashMap<String, Object>(); args.put(Param.TOKEN_TTL, TTL);//from w w w.j a v a2 s.c o m args.put(Param.API_KEY, mEta.getApiKey()); CookieSyncManager.createInstance(mEta.getContext()); CookieManager cm = CookieManager.getInstance(); String cookieString = cm.getCookie(ETA_COOKIE_DOMAIN); if (cookieString != null) { // No session yet, check cookies for old token String authId = null; String authTime = null; String authHash = null; String[] cookies = cookieString.split(";"); for (String cookie : cookies) { String[] keyValue = cookie.split("="); String key = keyValue[0].trim(); String value = keyValue[1]; if (value.equals("")) { continue; } if (key.equals(COOKIE_AUTH_ID)) { authId = value; } else if (key.equals(COOKIE_AUTH_HASH)) { authHash = value; } else if (key.equals(COOKIE_AUTH_TIME)) { authTime = value; } } // If all three fields are set, then try to migrate if (authId != null && authHash != null && authTime != null) { args.put(Param.V1_AUTH_ID, authId); args.put(Param.V1_AUTH_HASH, authHash); args.put(Param.V1_AUTH_TIME, authTime); } // Clear all cookie data, just to make sure cm.removeAllCookie(); } JsonObjectRequest req = new JsonObjectRequest(Method.POST, Endpoint.SESSIONS, new JSONObject(args), getSessionListener(l)); addRequest(req); }
From source file:com.example.sabeeh.helloworld.AuthService.java
/** * Handles logging the user out including: * -deleting cookies so their login with a provider won't be cached in the web view * -removing the userdata from the shared preferences * -setting the current user object on the client to logged out * -optionally redirects to the login page if requested * @param shouldRedirectToLogin/*from w w w . j av a 2 s. co m*/ */ public void logout(boolean shouldRedirectToLogin) { //Clear the cookies so they won't auto login to a provider again CookieSyncManager.createInstance(mContext); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); //Clear the user id and token from the shared preferences ClearcacheUserToken(); //Clear the user and return to the auth activity mClient.logout(); //Take the user back to the auth activity to relogin if requested if (shouldRedirectToLogin) { Intent logoutIntent = new Intent(mContext, LoginActivity.class); logoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(logoutIntent); } }