List of usage examples for org.apache.http.client CookieStore getCookies
List<Cookie> getCookies();
From source file:ro.teodorbaciu.commons.client.ws.BaseWsMethods.java
/** * Returns the cookie associated with the current webservice session. * //from w ww .ja v a 2s .co m * @return null if no cookie could be found */ public Cookie getCookie() { CookieStore cookieStore = wsHttpClient.getCookieStore(); if (cookieStore == null) { return null; } List<Cookie> listCookies = cookieStore.getCookies(); if (listCookies.size() == 0) { return null; } return listCookies.get(listCookies.size() - 1); }
From source file:com.revo.deployr.client.core.impl.RClientImpl.java
public RUser login(RAuthentication rAuthentication, boolean disableautosave) throws RClientException, RSecurityException { RCall rCall = null;/*from w ww .j av a 2 s . co m*/ if (rAuthentication instanceof RBasicAuthentication) { RBasicAuthentication basic = (RBasicAuthentication) rAuthentication; rCall = new LoginCall(basic.getUsername(), basic.getPassword(), disableautosave); } RCoreResult rResult = processCall(rCall); Map<String, String> identity = rResult.getIdentity(); Map<String, Integer> limits = rResult.getLimits(); // // Store cookie from response header, we no longer return this value in // the DeployR response markup as of `8.0.5` // CookieStore cookieStore = httpClient.getCookieStore(); Cookie cookie = cookieStore.getCookies().get(0); this.httpcookie = (cookie != null ? cookie.getValue() : null); // // - Store `X-XSRF-TOKEN` from `/r/uer/login` for future authenticated // requests // for (Header header : rResult.getHeaders()) { if (header.getName().equals(XSRF_HEADER)) { this.csrf = header.getValue(); } } RUserDetails userDetails = REntityUtil.getUserDetails(identity, limits, csrf); liveContext = new RLiveContext(this, serverurl, httpcookie); return new RUserImpl(userDetails, liveContext); }
From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java
public static String dumpCookieStore(CookieStore cookieStore) { StringBuilder cookies = new StringBuilder(); for (Cookie cookie : cookieStore.getCookies()) { System.out.println("CC**\n\n"); cookies.append(cookie.getName()); cookies.append("="); cookies.append(cookie.getValue()); cookies.append("="); cookies.append(cookie.getDomain()); cookies.append(";" + "\n"); }/* www.j a v a 2s . co m*/ return cookies.toString(); }
From source file:ti.modules.titanium.network.NetworkModule.java
/** * Removes all the cookies with the domain matched with the given value. * @param domain the domain of the cookie to remove. It is case-insensitive. *///from ww w . ja v a 2 s. co m @Kroll.method public void removeHTTPCookiesForDomain(String domain) { CookieStore cookieStore = getHTTPCookieStoreInstance(); List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies()); cookieStore.clear(); for (Cookie cookie : cookies) { String cookieDomain = cookie.getDomain(); if (!(domainMatch(cookieDomain, domain))) { cookieStore.addCookie(cookie); } } }
From source file:ti.modules.titanium.network.NetworkModule.java
/** Removes the cookie with the domain, path and name exactly the same as the given values. * @param domain the domain of the cookie to remove. It is case-insensitive. * @param path the path of the cookie to remove. It is case-sensitive. * @param name the name of the cookie to remove. It is case-sensitive. *//* w ww . ja v a 2 s. c om*/ @Kroll.method public void removeHTTPCookie(String domain, String path, String name) { if (domain == null || name == null) { if (Log.isDebugModeEnabled()) { Log.e(TAG, "Unable to remove the HTTP cookie. Need to provide a valid domain / name."); } return; } CookieStore cookieStore = getHTTPCookieStoreInstance(); List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies()); cookieStore.clear(); for (Cookie cookie : cookies) { String cookieName = cookie.getName(); String cookieDomain = cookie.getDomain(); String cookiePath = cookie.getPath(); if (!(name.equals(cookieName) && stringEqual(domain, cookieDomain, false) && stringEqual(path, cookiePath, true))) { cookieStore.addCookie(cookie); } } }
From source file:com.cognifide.qa.bb.aem.core.login.AemAuthCookieFactoryImpl.java
/** * This method provides browser cookie for authenticating user to AEM instance * * @param url URL to AEM instance, like http://localhost:4502 * @param login Username to use/*w ww . java 2 s.c o m*/ * @param password Password to use * @return Cookie for selenium WebDriver. */ @Override public Cookie getCookie(String url, String login, String password) { if (!cookieJar.containsKey(url)) { HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check"); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8")); nameValuePairs.add(new BasicNameValuePair("j_username", login)); nameValuePairs.add(new BasicNameValuePair("j_password", password)); nameValuePairs.add(new BasicNameValuePair("j_validate", "true")); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); try { loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context); loginResponse.close(); } catch (IOException e) { LOG.error("Can't get AEM authentication cookie", e); } finally { loginPost.reset(); } Cookie cookie = findAuthenticationCookie(cookieStore.getCookies()); if (cookie != null) { cookieJar.put(url, cookie); } } return cookieJar.get(url); }
From source file:com.bright.json.JSonRequestor.java
public static List<Cookie> doLogin(String user, String pass, String myURL) { try {/*from w ww .ja v a2 s.c o m*/ cmLogin loginReq = new cmLogin("login", user, pass); GsonBuilder builder = new GsonBuilder(); Gson g = builder.create(); String json = g.toJson(loginReq); /* HttpClient httpclient = new DefaultHttpClient(); */ HttpClient httpclient = getNewHttpClient(); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); /* httpclient = WebClientDevWrapper.wrapClient(httpclient); */ httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); HttpParams params = httpclient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 1000); HttpConnectionParams.setSoTimeout(params, 1000); HttpPost httppost = new HttpPost(myURL); StringEntity stringEntity = new StringEntity(json); stringEntity.setContentType("application/json"); httppost.setEntity(stringEntity); System.out.println("executing request " + httppost.getRequestLine()); HttpResponse response = httpclient.execute(httppost, localContext); System.out.println(response + "\n"); for (Cookie c : ((AbstractHttpClient) httpclient).getCookieStore().getCookies()) { System.out.println("\n Cookie: " + c.toString() + "\n"); } List<Cookie> cookies = cookieStore.getCookies(); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie: " + cookies.get(i)); } HttpEntity resEntity = response.getEntity(); System.out.println("----------------------------------------"); System.out.println(response.getStatusLine()); if (resEntity != null) { System.out.println("Response content length: " + resEntity.getContentLength()); System.out.println("Chunked?: " + resEntity.isChunked()); String message = new String(EntityUtils.toString(resEntity)); System.out.println(message); return cookies; } EntityUtils.consume(resEntity); } catch (Exception e) { e.printStackTrace(); return null; } return null; }
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession register(final String username, final String password, final String gender, final int birthMonth, final String birthYear, final String country, final String email) throws ScratchUserException { // Long if statement to verify all fields are valid if ((username.length() < 3) || (username.length() > 20) || (password.length() < 6) || (gender.length() < 2) || (birthMonth < 1) || (birthMonth > 12) || (birthYear.length() != 4) || (country.length() == 0) || (email.length() < 5)) { throw new ScratchUserException(); // TDL: Specify reason for failure } else {/*from w w w .j av a 2s. c o m*/ try { final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest csrf = RequestBuilder.get().setUri("https://scratch.mit.edu/csrf_token/") .addHeader("Accept", "*/*").addHeader("Referer", "https://scratch.mit.edu") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(csrf); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } try { resp.close(); } catch (final IOException e) { throw new ScratchUserException(); } String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); /* * try { * username = URLEncoder.encode(username, "UTF-8"); * password = URLEncoder.encode(password, "UTF-8"); * birthMonth = Integer.parseInt(URLEncoder.encode("" + * birthMonth, "UTF-8")); * birthYear = URLEncoder.encode(birthYear, "UTF-8"); * gender = URLEncoder.encode(gender, "UTF-8"); * country = URLEncoder.encode(country, "UTF-8"); * email = URLEncoder.encode(email, "UTF-8"); * } catch (UnsupportedEncodingException e1) { * e1.printStackTrace(); * } */ final BasicClientCookie csrfCookie = new BasicClientCookie("scratchcsrftoken", csrfToken); csrfCookie.setDomain(".scratch.mit.edu"); csrfCookie.setPath("/"); cookieStore.addCookie(csrfCookie); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(debug); httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); /* * final String data = "username=" + username + "&password=" + * password + "&birth_month=" + birthMonth + "&birth_year=" + * birthYear + "&gender=" + gender + "&country=" + country + * "&email=" + email + * "&is_robot=false&should_generate_admin_ticket=false&usernames_and_messages=%3Ctable+class%3D'banhistory'%3E%0A++++%3Cthead%3E%0A++++++++%3Ctr%3E%0A++++++++++++%3Ctd%3EAccount%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EEmail%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EReason%3C%2Ftd%3E%0A++++++++++++%3Ctd%3EDate%3C%2Ftd%3E%0A++++++++%3C%2Ftr%3E%0A++++%3C%2Fthead%3E%0A++++%0A%3C%2Ftable%3E%0A&csrfmiddlewaretoken=" * + csrfToken; * System.out.println(data); */ final MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("birth_month", birthMonth + "", ContentType.TEXT_PLAIN); builder.addTextBody("birth_year", birthYear, ContentType.TEXT_PLAIN); builder.addTextBody("country", country, ContentType.TEXT_PLAIN); builder.addTextBody("csrfmiddlewaretoken", csrfToken, ContentType.TEXT_PLAIN); builder.addTextBody("email", email, ContentType.TEXT_PLAIN); builder.addTextBody("gender", gender, ContentType.TEXT_PLAIN); builder.addTextBody("is_robot", "false", ContentType.TEXT_PLAIN); builder.addTextBody("password", password, ContentType.TEXT_PLAIN); builder.addTextBody("should_generate_admin_ticket", "false", ContentType.TEXT_PLAIN); builder.addTextBody("username", username, ContentType.TEXT_PLAIN); builder.addTextBody("usernames_and_messages", "<table class=\"banhistory\"> <thead> <tr> <td>Account</td> <td>Email</td> <td>Reason</td> <td>Date</td> </tr> </thead> </table>", ContentType.TEXT_PLAIN); final HttpUriRequest createAccount = RequestBuilder.post() .setUri("https://scratch.mit.edu/accounts/register_new_user/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu/accounts/standalone-registration/") .addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("DNT", "1") .addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8") .addHeader("X-Requested-With", "XMLHttpRequest").addHeader("X-CSRFToken", csrfToken) .addHeader("X-DevTools-Emulate-Network-Conditions-Client-Id", "54255D9A-9771-4CAC-9052-50C8AB7469E0") .setEntity(builder.build()).build(); resp = httpClient.execute(createAccount); System.out.println("REGISTER:" + resp.getStatusLine()); final BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); System.out.println("exact:" + result.toString() + "\n" + resp.getStatusLine().getReasonPhrase() + "\n" + resp.getStatusLine()); if (resp.getStatusLine().getStatusCode() != 200) throw new ScratchUserException(); resp.close(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } try { return Scratch.createSession(username, password); } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } } }
From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java
/** * cloudflare, cookie/*from w ww . j a v a 2 s. c o m*/ * @param exception Cloudflare ? * @param httpClient HTTP * @param task ?? * @param challenge challenge * @param recaptchaAnswer * @return ? cookie null, ? */ public Cookie checkRecaptcha(CloudflareException exception, ExtendedHttpClient httpClient, CancellableTask task, String challenge, String recaptchaAnswer) { if (!exception.isRecaptcha()) throw new IllegalArgumentException("wrong type of CloudflareException"); try { recaptchaAnswer = URLEncoder.encode(recaptchaAnswer, "UTF-8"); } catch (UnsupportedEncodingException e) { Logger.e(TAG, e); } String url = String.format(Locale.US, exception.getCheckCaptchaUrlFormat(), challenge, recaptchaAnswer); HttpResponseModel responseModel = null; try { HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setNoRedirect(false).build(); CookieStore cookieStore = httpClient.getCookieStore(); removeCookie(cookieStore, exception.getRequiredCookieName()); responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task); for (int i = 0; i < 3 && responseModel.statusCode == 400; ++i) { Logger.d(TAG, "HTTP 400"); responseModel.release(); responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task); } for (Cookie cookie : cookieStore.getCookies()) { if (isClearanceCookie(cookie, url, exception.getRequiredCookieName())) { Logger.d(TAG, "Cookie found: " + cookie.getValue()); return cookie; } } Logger.d(TAG, "Cookie is not found"); } catch (Exception e) { Logger.e(TAG, e); } finally { if (responseModel != null) { responseModel.release(); } } return null; }