private void download(String url) { try { mFile = FileUtil.getDestinationInExternalPublicDir( getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId)); PersistentCookieStore cookieStore = new PersistentCookieStore(AttachmentsDownloadDetailActivity.this); String cookieString = ""; for (Cookie cookie : cookieStore.getCookies()) { cookieString += cookie.getName() + "=" + cookie.getValue() + ";"; } DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url)); request.addRequestHeader("Cookie", cookieString); request.setDestinationInExternalPublicDir( getFileDownloadPath(), mFileObject.getSaveName(mProjectObjectId)); request.setTitle(mFileObject.getName()); // request.setDescription(mFileObject.name); // request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN); request.setVisibleInDownloadsUi(false); // request.allowScanningByMediaScanner(); // request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI); // request.setShowRunningNotification(false); downloadId = downloadManager.enqueue(request); downloadListEditor.putLong(mFileObject.file_id, downloadId); downloadListEditor.commit(); } catch (Exception e) { Toast.makeText(this, R.string.no_system_download_service, Toast.LENGTH_LONG).show(); } }
@Override public void process(HttpResponse response, HttpContext context) throws HttpException, IOException { CookieStore cookieStore = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE); for (Header header : response.getAllHeaders()) { if (!header.getName().equalsIgnoreCase("Set-Cookie")) { continue; } Matcher matcher = pattern.matcher(header.getValue()); if (!matcher.find()) { continue; } for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equalsIgnoreCase(matcher.group(1))) { if (cookie instanceof BasicClientCookie) { ((BasicClientCookie) cookie).setValue('"' + cookie.getValue() + '"'); } else if (cookie instanceof BasicClientCookie2) { ((BasicClientCookie2) cookie).setValue('"' + cookie.getValue() + '"'); } else { Log.w(TAG, "unhandled cookie implementation " + cookie.getClass().getName()); } break; } } } }
public String connectByPost(String url) { HttpPost httpPost = new HttpPost(url); System.out.println(url); try { // httpPost.addHeader("Referer", // "https://ui.ptlogin2.qq.com/cgi-bin/login?daid=164&target=self&style=5&mibao_css=m_webqq&appid=1003903&enable_qlogin=0&no_verifyimg=1&s_url=http%3A%2F%2Fweb2.qq.com%2Floginproxy.html&f_url=loginerroralert&strong_login=1&login_state=10&t=20131202001"); List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("ptwebqq")) { this.ptWebqq = cookie.getValue(); } } System.out.println(ptWebqq); httpPost.addHeader("clientid", "48847830"); httpPost.addHeader("psessionid", "null"); httpPost.addHeader( "r", "{\"status\":\"online\",\"ptwebqq\":\"" + this.ptWebqq + "\",\"passwd_sig\":\"\",\"clientid\":\"48847830\",\"psessionid\":null}"); CloseableHttpResponse response = this.httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); this.getContent = EntityUtils.toString(entity); response.close(); httpPost.abort(); } catch (Exception e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { return getContent; } }
private void cookieToPrefs(Cookie cookie, SyncedStore.Editor e) { final String name = cookie.getName(); e.putString(COOKIE_PREFIX + name + "value", cookie.getValue()); e.putString(COOKIE_PREFIX + name + "path", cookie.getPath()); e.putString(COOKIE_PREFIX + name + "domain", cookie.getDomain()); e.putString(COOKIE_PREFIX + name + "expiry", stringFromDate(cookie.getExpiryDate())); }
@Implementation public String getCookie(String url) { CookieOrigin origin = getOrigin(url); List<Cookie> matchedCookies = filter(origin); if (matchedCookies.isEmpty()) { return null; } StringBuffer cookieHeaderValue = new StringBuffer(); for (int i = 0, n = matchedCookies.size(); i < n; i++) { Cookie cookie = matchedCookies.get(i); if (i > 0) { cookieHeaderValue.append("; "); } cookieHeaderValue.append(cookie.getName()); String value = cookie.getValue(); if (value != null) { cookieHeaderValue.append("="); cookieHeaderValue.append(value); } } return cookieHeaderValue.toString(); }
/** * Non-standard helper method, to delete cookie * * @param cookie cookie to be removed */ public void deleteCookie(Cookie cookie) { String name = cookie.getName() + cookie.getDomain(); cookies.remove(name); SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.remove(COOKIE_NAME_PREFIX + name); prefsWriter.commit(); }
@Override public boolean clearExpired(Date date) { boolean clearedAny = false; SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) { String name = entry.getKey(); Cookie cookie = entry.getValue(); if (cookie.isExpired(date)) { // Clear cookies from local store cookies.remove(name); // Clear cookies from persistent store prefsWriter.remove(COOKIE_NAME_PREFIX + name); // We've cleared at least one clearedAny = true; } } // Update names in persistent store if (clearedAny) { prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); } prefsWriter.commit(); return clearedAny; }
@SuppressWarnings("deprecation") private void setCookie(Context context) { CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); cookieManager.setAcceptCookie(true); for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); String domainString = cookie.getDomain(); // Log.i("FRAGHOME",cookieName); // Log.i("FRAGHOME",cookieValue); // Log.i("FRAGHOME",domainString); if (!cookieName.isEmpty() && !cookieValue.isEmpty() && !domainString.isEmpty()) { cookieManager.setCookie(domainString, cookieName + "=" + cookieValue); } } // cookieManager.setCookie(baseURL, "uid=123"); CookieSyncManager.getInstance().sync(); if (cookieManager.getCookie(devbaseURL) != null) { System.out.println(cookieManager.getCookie(devbaseURL)); } // webview.loadUrl(baseURL+"?app-get_top_cate"); // System.out.println(cookieManager.getCookie(baseURL)); }
protected Map<String, String> getCookies() { Map<String, String> cookieMap = new CaseInsensitiveTreeMap(); for (Cookie cookie : this.httpClient.getCookieStore().getCookies()) { cookieMap.put(cookie.getName(), cookie.getValue()); } return cookieMap; }
/** * Checks there is no cookie in httpclient cookie store * * @param domain cookie domain * @param name cookie name * @param path cookie path * @throws Exception */ protected void assertNoCookie(String domain, String name, String path) throws Exception { Cookie expected = makeCookie(domain, name, null, path); for (Cookie cookie : getCookies()) { if (expected.equals(cookie)) { fail("Cookie was not deleted: " + cookie); } } }
// Obté cookie a partir d'un nom del client http especificat private Cookie getCookie(DefaultHttpClient cl, String name) { List<Cookie> cookies = cl.getCookieStore().getCookies(); for (int i = 0; i < cookies.size(); i++) { Cookie c = cookies.get(i); if (c.getName().equals(name)) return c; } return null; }
private Cookie getSessionCookie(Collection<Cookie> cookies) { for (Cookie cookie : cookies) { if ("JSESSIONID".equals(cookie.getName())) { return cookie; } } return null; }
private void clearAndAddPersistentCookies() { List<Cookie> cookies = new ArrayList<Cookie>(store.getCookies()); store.clear(); for (Cookie cookie : cookies) { if (cookie.isPersistent()) { store.addCookie(cookie); } } }
/** * Extract the sessionid cookie value * * @return sessionid string */ public String getSessionID() { String sid = null; String jsid = null; List<Cookie> cookies = this.sessioncontext.getCookieStore().getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equalsIgnoreCase("sessionid")) sid = cookie.getValue(); if (cookie.getName().equalsIgnoreCase("jsessionid")) jsid = cookie.getValue(); } return (sid == null ? jsid : sid); }
private void cookieToBundle(Cookie cookie, Bundle b) { final String name = cookie.getName(); b.putString(COOKIE_PREFIX + name + "value", cookie.getValue()); b.putString(COOKIE_PREFIX + name + "path", cookie.getPath()); b.putString(COOKIE_PREFIX + name + "domain", cookie.getDomain()); final Date expiryDate = cookie.getExpiryDate(); if (null != expiryDate) { b.putString(COOKIE_PREFIX + name + "expiry", stringFromDate(expiryDate)); } }
@Override public void writeExternal(ObjectOutput output) throws IOException { String data; Date date; List<Cookie> cookie_list = getCookies(); output.writeInt(cookie_list.size()); for (Cookie cookie : cookie_list) { output.writeUTF(cookie.getName()); output.writeUTF(cookie.getValue()); data = cookie.getComment(); output.writeBoolean(data != null); if (data != null) output.writeUTF(data); date = cookie.getExpiryDate(); output.writeBoolean(date != null); if (date != null) output.writeLong(date.getTime()); data = cookie.getDomain(); output.writeBoolean(data != null); if (data != null) output.writeUTF(data); data = cookie.getPath(); output.writeBoolean(data != null); if (data != null) output.writeUTF(data); output.writeBoolean(cookie.isSecure()); output.writeInt(cookie.getVersion()); } }
private boolean isPurlRunning() throws URISyntaxException, HttpException, ClientProtocolException, IOException { DefaultHttpClient client = new DefaultHttpClient(); URI url = new URI( "http://localhost:" + testInfo.getPurlzPort() + IdentifiersTestInfo.PURLZ_REST_LOGIN); HttpPost method = new HttpPost(url); List<NameValuePair> loginParams = new ArrayList<NameValuePair>(); loginParams.add(new BasicNameValuePair("id", IdentifiersTestInfo.PURLZ_USER)); loginParams.add(new BasicNameValuePair("passwd", IdentifiersTestInfo.PURLZ_PASSWORD)); loginParams.add(new BasicNameValuePair("referrer", "/docs/index.html")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(loginParams, "UTF-8"); method.setEntity(entity); try { System.out.println("isPurlRunning connecting to " + url); HttpResponse response = client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); System.out.println("PURL Login: HTTP Status code: " + statusCode); if (statusCode != HttpStatus.SC_OK) { throw new HttpException( " [" + statusCode + ":" + response.getStatusLine().toString() + "]"); } String responseStr = IdentifiersTestInfo.getResponseString(response); if (!responseStr.contains(IdentifiersTestInfo.PURLZ_WELCOME_MSG)) { System.out.println("BAD RESPONSE FROM SERVER [" + responseStr + "]"); return false; } System.out.println("Login to PURL successful..."); CookieStore store = client.getCookieStore(); for (Cookie cookie : store.getCookies()) { if (cookie.getName().equalsIgnoreCase(IdentifiersTestInfo.PURLZ_LOGIN_COOKIE)) { testInfo.setPurlzLoginCookie(cookie); return true; } } } finally { // Release the connection. method.abort(); client.getConnectionManager().shutdown(); } return false; }
/** Debug method to print cookies */ public void printCookies() { if (localContext != null) { CookieStore cookieStore = (CookieStore) localContext.getAttribute(ClientContext.COOKIE_STORE); if (cookieStore != null) { for (Cookie cookie : cookieStore.getCookies()) { Log.i(tag, "printCookie() >> current cookie is ============= " + cookie.getValue()); } } } Log.i(tag, "printCookie() >> current cookie is empty============= "); }
/** * Checks for cookie * * @param domain cookie domain * @param name cookie name * @param value cookie value * @param path cookie path * @throws Exception */ protected void assertCookie(String domain, String name, String path, String value) throws Exception { Cookie expected = makeCookie(domain, name, value, path); for (Cookie cookie : getCookies()) { if (expected.equals(cookie)) { assertEquals("Wrong cookie value!", expected.getValue(), cookie.getValue()); return; } } fail("Missing cookie, expected " + expected); }
// 检查过期时间 private boolean checkExperid(List<Cookie> cookies) { for (Cookie cookie : cookies) { if ("ue".equals(cookie.getName())) { Date now = new Date(); if (now.compareTo(cookie.getExpiryDate()) > 0) { return false; } } } return true; }
public void addCookie(Cookie cookie) { String name = cookie.getName(); if (cookie.isExpired(new Date())) { this.cookies.remove(name); } else { this.cookies.put(name, cookie); } Editor edit = this.cookiePrefs.edit(); edit.putString(COOKIE_NAME_STORE, TextUtils.join(",", this.cookies.keySet())); edit.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie))); edit.commit(); }
public Cookie getCookie(String name) { if (cookies == null || cookies.length == 0) { return null; } for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equalsIgnoreCase(name)) { return cookie; } } return null; }
private List<Cookie> filter(CookieOrigin origin) { List<Cookie> matchedCookies = new ArrayList<Cookie>(); Date now = new Date(); CookieSpec cookieSpec = createSpec(); for (Cookie cookie : store.getCookies()) { if (!cookie.isExpired(now)) { if (cookieSpec.match(cookie, origin)) { matchedCookies.add(cookie); } } } return matchedCookies; }
public void addCookie(Cookie paramCookie) { String str = paramCookie.getName(); if (!paramCookie.isExpired(new Date())) { this.cookies.put(str, paramCookie); } for (; ; ) { SharedPreferences.Editor localEditor = this.cookiePrefs.edit(); localEditor.putString("names", TextUtils.join(",", this.cookies.keySet())); localEditor.putString("cookie_" + str, encodeCookie(new SerializableCookie(paramCookie))); localEditor.commit(); return; this.cookies.remove(str); } }
@Override public void saveCookie(Cookie cookie) { if (cookie != null) { httpClient.getCookieStore().addCookie(cookie); if (canCloudflare()) { if (cookie.getName().equals(CLOUDFLARE_COOKIE_NAME)) { preferences .edit() .putString(getSharedKey(PREF_KEY_CLOUDFLARE_COOKIE), cookie.getValue()) .commit(); } } } }
private static CookieStore handleCsrfCookies(CookieStore cookieStore) { List<Cookie> cookies = new ArrayList<Cookie>(); for (Cookie cookie : cookieStore.getCookies()) { if (!cookie.getName().contains("CSRF")) { cookies.add(cookie); } } cookieStore.clear(); for (Cookie cookie : cookies) { cookieStore.addCookie(cookie); } return cookieStore; }
private void saveCookiesToPreferences(Context context, DefaultHttpClient client) { final SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME_SUMC_COOKIES, Context.MODE_PRIVATE); final Editor edit = sharedPreferences.edit(); edit.clear(); int i = 0; for (Cookie cookie : client.getCookieStore().getCookies()) { edit.putString(PREFERENCES_COOKIE_NAME + i, cookie.getName()); edit.putString(PREFERENCES_COOKIE_VALUE + i, cookie.getValue()); edit.putString(PREFERENCES_COOKIE_DOMAIN + i, cookie.getDomain()); edit.putString(PREFERENCES_COOKIE_PATH + i, cookie.getPath()); i++; } edit.commit(); }
public void addCookie(Cookie cookie) { String name = cookie.getName(); // Save cookie into local store, or remove if expired if (!cookie.isExpired(new Date())) { cookies.put(name, cookie); } else { cookies.remove(name); } // Save cookie into persistent store SharedPreferences.Editor prefsWriter = cookiePrefs.edit(); prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet())); prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie))); prefsWriter.commit(); }
public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } String targetpath = origin.getPath(); String topmostPath = cookie.getPath(); if (topmostPath == null) { topmostPath = "/"; } if (topmostPath.length() > 1 && topmostPath.endsWith("/")) { topmostPath = topmostPath.substring(0, topmostPath.length() - 1); } boolean match = targetpath.startsWith(topmostPath); // if there is a match and these values are not exactly the same we have // to make sure we're not matcing "/foobar" and "/foo" if (match && targetpath.length() != topmostPath.length()) { if (!topmostPath.endsWith("/")) { match = (targetpath.charAt(topmostPath.length()) == '/'); } } return match; }
/** Adds valid Port attribute value, e.g. "8000,8001,8002" */ @Override protected void formatCookieAsVer( final CharArrayBuffer buffer, final Cookie cookie, final int version) { super.formatCookieAsVer(buffer, cookie, version); // format port attribute if (cookie instanceof ClientCookie) { // Test if the port attribute as set by the origin server is not blank final String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR); if (s != null) { buffer.append("; $Port"); buffer.append("=\""); if (s.trim().length() > 0) { final int[] ports = cookie.getPorts(); if (ports != null) { final int len = ports.length; for (int i = 0; i < len; i++) { if (i > 0) { buffer.append(","); } buffer.append(Integer.toString(ports[i])); } } } buffer.append("\""); } } }