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; } } } }
/** * 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); }
/** * 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); }
@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(); }
@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; }
@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()); } }
protected synchronized void clearCookieForHost(String sessionHost) throws Exception { Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { String cookieDomain = cookie.getDomain(); if (cookieDomain != null) { if (sessionHost.equals(cookieDomain) || sessionHost.indexOf(cookieDomain) != -1 || cookieDomain.indexOf(sessionHost) != -1) { sessionCookie = cookie; break; } } } if (sessionCookie != null) { BasicClientCookie httpCookie = new BasicClientCookie(sessionCookie.getName(), sessionCookie.getValue()); httpCookie.setExpiryDate(new Date(0)); httpCookie.setVersion(1); httpCookie.setPath(sessionCookie.getPath()); httpCookie.setDomain(sessionCookie.getDomain()); cookieStore.addCookie(httpCookie); } cookieStore.clearExpired(new Date()); // this should clear the cookie }
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())); }
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; } }
public static void login(Map<String, String> connConf, String userName, String pwd) { String checkImgPage = "https://webim.feixin.10086.cn/WebIM/GetPicCode.aspx?Type=ccpsession&0.6949566061972312"; String check = getChkImage(checkImgPage); connConf.put("check", check); String loginUrl = "https://webim.feixin.10086.cn/WebIM/Login.aspx"; Map<String, String> postData = new HashMap<String, String>(); postData.put("Ccp", check); postData.put("OnlineStatus", "400"); postData.put("Pwd", pwd); postData.put("UserName", userName); postText(loginUrl, postData); String ssid = null; CookieStore cookieStroe = getCookieStroe(); List<Cookie> cookies = cookieStroe.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("webim_sessionid")) { ssid = cookie.getValue(); connConf.put("ssid", ssid); log.debug("webim_sessionid:" + ssid); } } String preQueryUidUrl = "https://webim.feixin.10086.cn/content/WebIM/GetPicCode.aspx?Type=addbuddy_ccpsession&0.7922769554654019"; getText(preQueryUidUrl); String ccpId = null; String ccpsession = null; cookies = cookieStroe.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().equals("addbuddy_ccpsession")) { ccpId = cookie.getValue(); connConf.put("ccpId", ccpId); // cookies.remove(cookie); log.debug("addbuddy_ccpsession:" + ccpId); } if (cookie.getName().equals("ccpsession")) { ccpsession = cookie.getValue(); // cookies.remove(cookie); log.debug("ccpsession:" + ccpsession); } } }
private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(cookie.getName()); out.writeObject(cookie.getValue()); out.writeObject(cookie.getComment()); out.writeObject(cookie.getDomain()); out.writeObject(cookie.getExpiryDate()); out.writeObject(cookie.getPath()); out.writeInt(cookie.getVersion()); out.writeBoolean(cookie.isSecure()); }
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)); } }
/** * Creates a new HtmlUnit cookie from the HttpClient cookie provided. * * @param c the HttpClient cookie */ public Cookie(final org.apache.http.cookie.Cookie c) { this( c.getDomain(), c.getName(), c.getValue(), c.getPath(), c.getExpiryDate(), c.isSecure(), ((ClientCookie) c).getAttribute("httponly") != null); }
/** 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============= "); }
@Override public synchronized void addCookie(Cookie cookie) { super.addCookie(cookie); String name = cookie.getName(); Cookie existing = null; SyncedStore.Reader r = mSharedPreferences.read(); try { existing = cookieFromPrefs(r, name); } finally { r.complete(); } if (existing == null || !existing.getValue().equals(cookie.getValue()) || !existing.getPath().equals(cookie.getPath()) || !existing.getDomain().equals(cookie.getDomain()) || !existing.getExpiryDate().equals(cookie.getExpiryDate())) { SyncedStore.Editor e = mSharedPreferences.edit(); try { // clear the existing cookie from prefs. String prefix = COOKIE_PREFIX + name; for (String k : e.keySet()) { if (k.startsWith(prefix)) { e.remove(k); } } // and then, if new cookie is persistent, then add it! if (cookie.getExpiryDate() != null) { cookieToPrefs(cookie, e); } } finally { e.commit(); } } }
@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 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(); }
@Override public void retrieve() throws RetrieverException { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient .getParams() .setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpContext context = new BasicHttpContext(); accounts = new HashMap<String, Account>(); try { CookieStore cookieStore = httpClient.getCookieStore(); BasicClientCookie newCookie = new BasicClientCookie("XPRDMBP1E", registrationCookie); newCookie.setVersion(0); newCookie.setDomain("bankservices.rabobank.nl"); newCookie.setPath("/"); cookieStore.addCookie(newCookie); if (!checkAppStatus(httpClient, context)) { throw new RetrieverException("Application status is not OK"); } if (!loginWithAccessCode(httpClient, context, accountNumber, accessCode)) { throw new RetrieverException("Login with access code failed", true); } List<Account> accountList = retrieveAccounts(httpClient, context); logoff(httpClient, context); accounts = new HashMap<String, Account>(); for (Account account : accountList) { accounts.put(account.getAccountName(), account); } for (Cookie cookie : httpClient.getCookieStore().getCookies()) { if ("XPRDMBP1E".equals(cookie.getName())) { registrationCookie = cookie.getValue(); } } } catch (IOException e) { throw new RetrieverException(e); } }
/** * 检测账号是否需要验证码 * * @param context * @param user * @return 0,不需要 1,需要 */ public static int checkVerify(Context context, String user) { HttpResult verResult = HttpClientHelper.get( VER_CODE_URL, null, new NameValuePair[] { new BasicNameValuePair("u", user), new BasicNameValuePair("cachetime", String.valueOf(System.currentTimeMillis())) }); Cookie verCodeCookie = verResult.getCookie(CHECK_RESULT); String checkResult = verCodeCookie.getValue(); System.out.println("CHECK_RESULT:" + checkResult); saveDefaultVerify(context, checkResult.substring(checkResult.indexOf(":") + 1)); if (checkResult.charAt(0) == '0') { String VERIFY_KEY = verResult.getCookie("VERIFY_KEY").getValue(); saveUserKey(context, VERIFY_KEY); return 0; } return 1; }
public static Bitmap getVerify(Context context) { String url = "http://verify.xunlei.com/image?cachetime=" + System.currentTimeMillis(); System.out.println("获取验证码===>>>" + url); HttpResult result = HttpClientHelper.get(url); byte[] data = null; if (result != null && result.getStatuCode() == HttpStatus.SC_OK) { Cookie cookie = result.getCookie("VERIFY_KEY"); data = result.getResponse(); if (cookie == null) { return null; } String value = cookie.getValue(); System.out.println(value); saveUserKey(context, value); } Bitmap bm = null; if (data != null) { ByteArrayInputStream is = new ByteArrayInputStream(data); bm = BitmapFactory.decodeStream(is); } return bm; }
/** * 获取标准 Cookie ,并存储 * * @param httpClient */ private void getCookie(DefaultHttpClient httpClient) { List<Cookie> cookies = httpClient.getCookieStore().getCookies(); // StringBuffer sb = new StringBuffer(); for (int i = 0; i < cookies.size(); i++) { Cookie cookie = cookies.get(i); String cookieName = cookie.getName(); String cookieValue = cookie.getValue(); if (!TextUtils.isEmpty(cookieName) && !TextUtils.isEmpty(cookieValue)) { if ("JSESSIONID".equalsIgnoreCase(cookieName)) { JSESSIONIDStr = cookieValue; } } } // Log. e( "cookie", sb.toString()); if (JSESSIONIDStr != null && !"".equals(JSESSIONIDStr)) { appContext .getSharedPreferences(BaseActivity.SETTING_INFOS, 0) .edit() .putString(BaseActivity.COOKIES_STR, JSESSIONIDStr) .commit(); } }
private Response doRequest(final HttpRequestBase request, final DefaultHttpClient httpClient) { final Response response = new Response(); int resultCode; try { HttpResponse httpResponse = httpClient.execute(request); InputStream stream = httpResponse.getEntity().getContent(); response.setStreamString(RequestUtils.convertStreamToString(stream)); Header[] headers = httpResponse.getAllHeaders(); if (headers != null && headers.length != 0) { for (Header header : headers) { response.setHeader(header.getName(), header.getValue()); } } List<Cookie> cookies = httpClient.getCookieStore().getCookies(); if (cookies != null && !cookies.isEmpty()) { for (Cookie cookie : cookies) { response.setCookies(cookie.getName(), cookie.getValue()); } } resultCode = httpResponse.getStatusLine().getStatusCode(); if (resultCode == 200 || resultCode == 302) { response.setStatus(ResponseStatus.SUCCESS); } else { response.setStatus(ResponseStatus.FAILED); } response.setResultCode(resultCode); return response; } catch (final Exception ex) { // TO DO: create types of response statuses for all kind of exceptions return buildErrorResponse(ex.getMessage(), ResponseStatus.FAILED); } }
public String getValue() { return cookie.getValue(); }
/** * http网页内容抓取 * * @param url String 网页地址 * @param timeoutSeconds int 超时时间(单位秒) * @param params Map<String, String> HTTPHead参数 * @param cookieStore CookieStore 网页cookie * @return */ public static String sendGet( Context mContext, String url, int timeoutSeconds, Map<String, String> params, CookieStore cookieStore, boolean isSaveCookie) { String result = null; Log.v(TAG, "httpGet start to get url:" + url); HttpParams httpParams = new BasicHttpParams(); HttpContext context = new BasicHttpContext(); DefaultHttpClient httpClient = new DefaultHttpClient(httpParams); WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); if (!wifiManager.isWifiEnabled()) { Uri uri = Uri.parse("content://telephony/carriers/preferapn"); // 获取当前正在使用的APN接入点 Cursor mCursor = mContext.getContentResolver().query(uri, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToNext(); String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy")); if (proxyStr != null && proxyStr.trim().length() > 0) { Log.v(TAG, "wap proxy:" + proxyStr); HttpHost proxy = new HttpHost(proxyStr, 80); httpClient.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy); } } } HttpConnectionParams.setConnectionTimeout(httpParams, timeoutSeconds * 1000); HttpConnectionParams.setSoTimeout(httpParams, timeoutSeconds * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8192); HttpClientParams.setCookiePolicy(httpClient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY); if (cookieStore != null) { httpClient.setCookieStore(cookieStore); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } HttpGet httpGet = new HttpGet(url); httpGet.setHeader( "User-Agent", "Mozilla/5.0 (Linux; U; Android " + Build.VERSION.RELEASE + "; Zh-cn; " + Build.MODEL + " )AppleWebKit/528.5+(KHTML,like Gecko)Version/3.1.2 Mobile Safari/525.20.1"); if (params != null) { Iterator<String> ite = params.keySet().iterator(); while (ite.hasNext()) { String key = (String) ite.next(); String value = (String) params.get(key); httpGet.addHeader(key, value); } } try { HttpResponse response = httpClient.execute(httpGet, context); if (isSaveCookie) { CookieStore cookieStores = httpClient.getCookieStore(); if (cookieStores != null) { List<Cookie> listCookie = cookieStores.getCookies(); int len = listCookie.size(); for (int i = 0; i < len; i++) { Cookie cookie = listCookie.get(i); StringBuffer sb = new StringBuffer(); sb.append(cookie.getName() + "=" + cookie.getValue() + ";\n"); sb.append("domain=" + cookie.getDomain() + ";\n"); sb.append("path=" + cookie.getPath() + ";\n"); sb.append("expiry=" + cookie.getExpiryDate() + ";\n"); Log.i(TAG, sb.toString()); } } // Config.getInstance().setCookieStroe(httpClient.getCookieStore()); } int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { result = EntityUtils.toString(response.getEntity()); } else { Log.v(TAG, "result:" + EntityUtils.toString(response.getEntity())); result = MessageModel.RESPONSE_EXCEPTION; Log.e(TAG, "Network Exception, statusCode:" + statusCode); } } catch (Exception e) { if (e instanceof SocketTimeoutException) { result = MessageModel.CONNECTION_TIMEOUT; Log.e(TAG, "CONNECTION_TIMEOUT---- Network Exception:" + e.getMessage() + " url:" + url); e.printStackTrace(); } else { result = MessageModel.RESPONSE_EXCEPTION; Log.e(TAG, "RESPONSE_EXCEPTION ---- Network Exception:" + e.getMessage() + " url:" + url); e.printStackTrace(); } } finally { httpClient.getConnectionManager().shutdown(); } Log.v(TAG, "httpGet get result:" + result); return result; }
public boolean login() throws HTTPException { LoginParameters loginParameters = new LoginParameters(); // Check the client cookies. If 'enwikiUserID', 'enwikiUserName', and 'centralauth_Token' are // valid, already logged in. List<Cookie> cookies = client.getCookieStore().getCookies(); int numCookieFound = 0; Iterator<Cookie> cookieItr = cookies.iterator(); while (cookieItr.hasNext()) { Cookie cookie = cookieItr.next(); if (cookie.getName().equalsIgnoreCase("enwikiUserID")) numCookieFound++; else if (cookie.getName().equalsIgnoreCase("enwikiUsername")) numCookieFound++; else if (cookie.getName().equalsIgnoreCase("centralauth_Token")) numCookieFound++; if (numCookieFound == 3) return true; } // Send the initial login request String loginQuery = url + "api.php?action=login&lgname=" + username + "&lgpassword="******"&format=xml"; HttpPost loginRequest = new HttpPost(loginQuery); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody; try { responseBody = client.execute(loginRequest, responseHandler); } catch (ClientProtocolException e) { throw new HTTPException("An HTTP protocol error occurred."); } catch (IOException e) { e.printStackTrace(); throw new HTTPException("The connection was aborted."); } loginParameters.setXMLParameters(responseBody); // Send the confirm token request String confirmTokenQuery = url + "api.php?action=login&lgname=" + username + "&lgpassword="******"&lgtoken=" + loginParameters.getToken() + "&format=xml"; HttpPost confirmTokenRequest = new HttpPost(confirmTokenQuery); try { responseBody = client.execute(confirmTokenRequest, responseHandler); } catch (ClientProtocolException e) { throw new HTTPException("An HTTP protocol error occurred."); } catch (IOException e) { throw new HTTPException("The connection was aborted."); } loginParameters.setXMLParameters(responseBody); // Save the cookie information. cookies = client.getCookieStore().getCookies(); cookieItr = cookies.iterator(); ArrayList<String> cookieInfo = new ArrayList<String>(); while (cookieItr.hasNext()) { Cookie cookie = cookieItr.next(); if (cookie.isPersistent() && !cookie.isExpired(new Date())) { String cookieDetails = cookie.getComment() + "," + cookie.getCommentURL() + "," + cookie.getDomain() + "," + cookie.getName() + "," + cookie.getPath() + "," + cookie.getValue() + "," + cookie.getVersion() + "," + cookie.getExpiryDate().toString(); cookieInfo.add(cookieDetails); } } addCookiesToFile(cookieInfo); return false; }
// Retorna el httpclient. Si no està establerta la connexió, l'estableix private DefaultHttpClient getHttpClient() throws ServerError { // Primer comprovem si ja tenim el client en caché // També si ha passat manco de mitja hora des de la darrera vegada. if (client != null) { Date now = new Date(); Long dif = now.getTime() - lastDate.getTime(); Log.v(TAG, "Client object exists. Lastdate=" + String.valueOf(dif)); if (dif < 1800000) { Log.v(TAG, "Client is valid. Returning from cache"); lastDate = now; return client; } } // La idea és la següent: // // Primer fem un get a https://apps.esliceu.com/auth/login // Això ens serveix per emmagazemar les cookies. N'hi ha dues: sessionid i csrftoken // Després, hem de fer un post a https://apps.esliceu.com/auth/login, transmitint també les // cookies anteriors // Dins aquest post hem d'especificar les variables "username", "password" i // "csrfmiddlewaretoken" // Aquesta darrera variable té el mateix valor que el nom de la cookie csrftoken Log.v(TAG, "Beginning authorization..."); DefaultHttpClient myclient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet("https://apps.esliceu.com/auth/login/"); try { HttpResponse response = myclient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); response.getEntity().consumeContent(); if (statusLine.getStatusCode() != 200) throw new ServerError(); Cookie ck = getCookie(myclient, "csrftoken"); if (ck == null) throw new ServerError(); String token = ck.getValue(); Log.v(TAG, "csr: " + token); ck = getCookie(myclient, "sessionid"); if (ck == null) throw new ServerError(); String sid = ck.getValue(); Log.v(TAG, "sessionid: " + sid); HttpPost httpost = new HttpPost("https://apps.esliceu.com/auth/login/"); httpost.addHeader("Referer", "https://apps.esliceu.com/auth/login/"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", username)); nvps.add(new BasicNameValuePair("password", password)); nvps.add(new BasicNameValuePair("csrfmiddlewaretoken", token)); httpost.setEntity(new UrlEncodedFormEntity(nvps)); response = myclient.execute(httpost); response.getEntity().consumeContent(); Log.v(TAG, "Status: " + String.valueOf(response.getStatusLine().getStatusCode())); if (response.getStatusLine().getStatusCode() == 200) { // Comprovem que la sessionid ha canviat // Si no ha canviat és que no ha anat bé l'autorització Cookie ck2 = getCookie(myclient, "sessionid"); if (ck2 == null) throw new ServerError(); if (ck2.getValue().equals(sid)) throw new ServerError(); Log.v(TAG, "AUTHORIZED!"); client = myclient; lastDate = new Date(); return myclient; } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } throw new ServerError(); }
public InputStream executeRequest(String paramString1, HashMap<String, String> paramHashMap1, HashMap<String, String> paramHashMap2, String paramString2) throws FabException { InputStream localInputStream = null; ArrayList localArrayList = new ArrayList(); Iterator localIterator3; if (paramHashMap2 != null) localIterator3 = paramHashMap2.keySet().iterator(); while (true) { if (!localIterator3.hasNext()); try { HttpResponse localHttpResponse = getThreadSafeClient().execute(getDefaultMethod(paramString1, localArrayList, paramString2), getFabHttpContext()); HttpEntity localHttpEntity = localHttpResponse.getEntity(); if ((!paramString1.contains("cdn1." + FabEnvironment.baseUrl() + "/")) && ((paramString1.contains("." + FabEnvironment.baseUrl() + "/")) || (paramString1.contains("/" + FabEnvironment.baseUrl() + "/")))) { List localList = cookieStore.getCookies(); if (!localList.isEmpty()) { localIterator1 = localList.iterator(); if (localIterator1.hasNext()) break label361; localStringBuilder = new StringBuilder(); localIterator2 = fabCookieHash.keySet().iterator(); if (localIterator2.hasNext()) break label545; FabSharedPrefs.setFabCookies(localStringBuilder.toString()); } } localInputStream = localHttpEntity.getContent(); int i = localHttpResponse.getStatusLine().getStatusCode(); if ((i < 200) || (i > 207)) throw new FabException("Unable to contact server" + localHttpResponse.getStatusLine().getReasonPhrase()); } catch (HttpResponseException localHttpResponseException) { while (true) { Iterator localIterator1; return localInputStream; String str2 = (String)localIterator3.next(); BasicNameValuePair localBasicNameValuePair = new BasicNameValuePair(str2, (String)paramHashMap2.get(str2)); localArrayList.add(localBasicNameValuePair); break; Cookie localCookie = (Cookie)localIterator1.next(); if ((localCookie.getDomain().contains(FabEnvironment.baseDomain())) && (!localCookie.getName().contains("fab_session"))) fabCookieHash.put(localCookie.getName(), localCookie.getName() + "=" + localCookie.getValue() + "; domain=" + localCookie.getDomain() + "<@@>" + localCookie.getName() + "<##>" + localCookie.getValue() + "<##>" + localCookie.isSecure() + "<##>" + localCookie.getVersion()); } } catch (ClientProtocolException localClientProtocolException) { while (true) { Iterator localIterator2; throw new FabException(localClientProtocolException); str1 = (String)localIterator2.next(); if ((!paramString1.contains("stay-signed-in/?enable=0")) || (!"tla".equalsIgnoreCase(str1))) break; fabCookieHash.remove(str1); } } catch (IOException localIOException) { while (true) { StringBuilder localStringBuilder; String str1; throw new FabException(localIOException); localStringBuilder.append((String)fabCookieHash.get(str1)); localStringBuilder.append("<==>"); } } catch (Exception localException) { label361: localException.toString(); label545: throw new FabException(localException); } } }
public static void main(String args[]) throws Exception { String username = "******"; String password = "******"; CookieStore cookieStore = new BasicCookieStore(); CloseableHttpClient httpClient = Tools.createSSLClientDefaultWithCookie(cookieStore); // 初始化结果 String result = ""; String url = ""; List<NameValuePair> params = new ArrayList<NameValuePair>(); HttpEntity httpEntity; String imageCode = ""; // 取参数 url = "https://user.qunar.com/passport/login.jsp"; result = EntityUtils.toString(httpClient.execute(new HttpGet(url)).getEntity()); Document doc = Jsoup.parse(result); String imageCodeUrl = doc.select("#vcodeImg").attr("src"); // 判断是否需要图片验证码 url = "https://user.qunar.com/webApi/isNeedCaptcha.jsp?username="******"Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); result = EntityUtils.toString(httpClient.execute(httpPost).getEntity()); // not need {"data":false,"errcode":200,"ret":true,"ver":1} // need {"data":true,"errcode":200,"ret":true,"ver":1} if (result.contains("\"data\":false")) { // 开始登录 url = "https://user.qunar.com/passport/loginx.jsp"; httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); params.add(new BasicNameValuePair("loginType", "0")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("remember", "0")); params.add(new BasicNameValuePair("vcode", imageCode)); httpEntity = new UrlEncodedFormEntity(params); httpPost.setEntity(httpEntity); result = EntityUtils.toString(httpClient.execute(httpPost).getEntity()); } while (result.contains("\"data\":true") || result.contains("验证码错误")) { URL imageURL = new URL(imageCodeUrl); URI uri = new URI( imageURL.getProtocol(), imageURL.getHost(), imageURL.getPath(), imageURL.getQuery(), null); Tools.saveToLocal(httpClient.execute(new HttpGet(uri)).getEntity(), "qunar.png"); imageCode = JOptionPane.showInputDialog("请输入图片验证码!"); // 开始登录 url = "https://user.qunar.com/passport/loginx.jsp"; httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); params.add(new BasicNameValuePair("loginType", "0")); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); params.add(new BasicNameValuePair("remember", "0")); params.add(new BasicNameValuePair("vcode", imageCode)); httpEntity = new UrlEncodedFormEntity(params); httpPost.setEntity(httpEntity); result = EntityUtils.toString(httpClient.execute(httpPost).getEntity()); } // loginResult:{"data":{"needCaptcha":true},"errcode":11004,"errmsg":"验证码错误","ret":false,"ver":0} // {"data":{"needCaptcha":true},"errcode":21022,"errmsg":"用户名或密码错误","ret":false,"ver":0} System.out.println("result:" + result); // basic url = "http://user.qunar.com/userinfo/basic.jsp"; byte[] bytes = EntityUtils.toByteArray(httpClient.execute(new HttpGet(url)).getEntity()); result = new String(bytes); System.out.println("result:" + result); Tools.saveToLocalByBytes(bytes, "qunar.basic.html"); String csrfTokenParam = ""; List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { if (cookie.getName().contains("csrfToken")) { csrfTokenParam = cookie.getValue(); } } // billist url = "http://tinfo.qunar.com/order/queryByUser.json?callback"; params.add(new BasicNameValuePair("showCookie", "1")); params.add(new BasicNameValuePair("pageSize", "10000")); params.add(new BasicNameValuePair("currentPage", "1")); params.add(new BasicNameValuePair("csrfTokenParam", csrfTokenParam)); params.add(new BasicNameValuePair("startDate", "2013-01-22")); params.add(new BasicNameValuePair("endDate", "2014-07-22")); params.add(new BasicNameValuePair("status", "-1")); httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); bytes = EntityUtils.toByteArray(httpClient.execute(httpPost).getEntity()); result = new String(bytes); System.out.println("result:" + result); Tools.saveToLocalByBytes(bytes, "qunar.billlist.html"); // 保存详单. JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(result.replace(")", "").replace("(", "")); JsonArray orders = jsonElement.getAsJsonObject().get("list").getAsJsonArray(); int i = 1; for (JsonElement order : orders) { String orderNo = order.getAsJsonObject().get("orderNo").getAsString(); String ota = order.getAsJsonObject().get("ota").getAsString(); url = "http://tinfo.qunar.com/order/redirect2Detail?orderNo=" + orderNo + "&otaType=1&ota=" + ota; System.out.println("orderNo:" + orderNo); Tools.saveToLocalByBytes(bytes, "qunar.bill" + i + ".html"); i++; result = new String(bytes); System.out.println("result:" + result); } }