List of usage examples for org.apache.http.client CookieStore addCookie
void addCookie(Cookie cookie);
From source file:com.gooddata.http.client.CookieUtils.java
private static void replaceSst(final String sst, final CookieStore cookieStore, final String domain) { final BasicClientCookie cookie = new BasicClientCookie(SST_COOKIE_NAME, sst); cookie.setSecure(true);//from ww w .j av a 2 s . com cookie.setPath(SST_COOKIE_PATH); cookie.setDomain(domain); cookieStore.addCookie(cookie); }
From source file:gov.nih.nci.firebird.commons.selenium2.util.FileDownloadUtils.java
private static void setupCookies(DefaultHttpClient client, WebDriver driver) { CookieStore cookieStore = new BasicCookieStore(); for (Cookie webDriverCookie : driver.manage().getCookies()) { cookieStore.addCookie(translateCookie(webDriverCookie)); }//from w ww. j a va2 s .c o m client.setCookieStore(cookieStore); }
From source file:com.kms.core.io.HttpUtil_In.java
public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) { CloseableHttpClient httpclient;/*from w w w . j a va2s. c o m*/ // Auth Scheme final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create() .register(AuthSchemes.NTLM, new NTLMSchemeFactory()) .register(AuthSchemes.BASIC, new BasicSchemeFactory()) .register(AuthSchemes.DIGEST, new DigestSchemeFactory()) .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory()) .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build(); // NTLM final CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080), new NTCredentials(SoeID, Password, "dummy", "APAC")); //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" )); // ------------- cookie start ------------------------ // Auction // Create a local instance of cookie store final CookieStore cookieStore = new BasicCookieStore(); // Cookie . final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES"); cookie.setVersion(0); cookie.setDomain(".scourt.go.kr"); cookie.setPath("/"); cookieStore.addCookie(cookie); // ------------- cookie end ------------------------ if (type == 0) // TYPE.AuctionInput { // HTTP Client httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credsProvider).build(); } else // SagunInput { // HTTP Client httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry) .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build(); } return httpclient; }
From source file:parlare.application.server.controller.ControllerFunctions.java
public static String listCookies(String method, String listCookies) throws IOException { String printHTML = ""; switch (method) { case "javascript": printHTML += "<script>"; printHTML += "function setCookie(name,value,days) { "; printHTML += "var expires = \"\"; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = \"; expires=\" + date.toGMTString(); } "; printHTML += "document.cookie = name + \"=\" + value + expires + \"; path=/\";"; printHTML += "} "; printHTML += "function getCookie(name) { var nameEQ = name + \"=\"; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; "; printHTML += "while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } "; printHTML += "function eraseCookie(name) { setCookie(name, \"\", -1); } "; printHTML += "</script>"; if (listCookies != null) { String[] tokens = listCookies.split(";"); printHTML += "<script>"; for (String token : tokens) { String[] data = token.trim().split("="); if (data.length == 2) { printHTML += " setCookie('" + data[0] + "', '" + data[1] + "', 60);"; }/*from w w w.j a v a 2 s .c o m*/ } printHTML += "</script>"; } break; case "java": DefaultHttpClient httpClient = new DefaultHttpClient(); CookieStore cookieStore = httpClient.getCookieStore(); BasicClientCookie cookie = new BasicClientCookie("HelpMeUniverse", "I need your help my dear universe"); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 100); cookie.setExpiryDate(calendar.getTime()); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); // Prepare a request object HttpGet httpGet = new HttpGet("http://localhost/"); // Execute the request HttpResponse httpResponse = httpClient.execute(httpGet); // Examine the response status System.out.println("Http request response is: " + httpResponse.getStatusLine()); break; } return printHTML; }
From source file:edu.mit.scratch.ScratchStatistics.java
protected static JSONObject getStatisticsJSONObject() throws ScratchStatisticalException { try {// w w w . j a v a2s .c o m final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(debug); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://scratch.mit.edu/statistics/data/daily/") .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchStatisticalException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchStatisticalException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); return new JSONObject(result.toString().trim()); } catch (final UnsupportedEncodingException e) { e.printStackTrace(); throw new ScratchStatisticalException(); } catch (final Exception e) { e.printStackTrace(); throw new ScratchStatisticalException(); } }
From source file:com.ggasoftware.uitest.utils.FileUtil.java
/** * Get Cookie from WebDriver browser session. * * @return cookieStore from WebDriver browser session. *///from www . ja v a 2s . co m private static CookieStore seleniumCookiesToCookieStore() { Set<Cookie> seleniumCookies = WebDriverWrapper.getDriver().manage().getCookies(); CookieStore cookieStore = new BasicCookieStore(); for (Cookie seleniumCookie : seleniumCookies) { BasicClientCookie basicClientCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue()); basicClientCookie.setDomain(seleniumCookie.getDomain()); basicClientCookie.setExpiryDate(seleniumCookie.getExpiry()); basicClientCookie.setPath(seleniumCookie.getPath()); cookieStore.addCookie(basicClientCookie); } return cookieStore; }
From source file:net.niyonkuru.koodroid.service.SessionService.java
/** * Adds a province cookie to the {@link CookieStore} of the {@link DefaultHttpClient} object. This will stop the * Koodo Servers from prompting us with region selection on login. *//* ww w .j av a 2s .c om*/ private static void setProvinceCookie(DefaultHttpClient httpClient) { CookieStore cookieStore = httpClient.getCookieStore(); BasicClientCookie cookie = new BasicClientCookie("prov", "on"); cookie.setDomain("." + Config.DOMAIN); cookie.setPath("/"); cookieStore.addCookie(cookie); }
From source file:com.bright.json.JSonRequestor.java
public static String doRequest(String jsonReq, String myURL, List<Cookie> cookies) { try {/*from w w w . j av a 2 s. c o m*/ /* HttpClient httpclient = new DefaultHttpClient(); */ HttpClient httpclient = getNewHttpClient(); CookieStore cookieStore = new BasicCookieStore(); Cookie[] cookiearray = cookies.toArray(new Cookie[0]); cookieStore.addCookie(cookiearray[0]); 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(jsonReq); stringEntity.setContentType("application/json"); httppost.setEntity(stringEntity); System.out.println("executing request " + httppost.getRequestLine() + System.getProperty("line.separator") + jsonReq); 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"); } 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 message; } EntityUtils.consume(resEntity); } catch (Exception e) { e.printStackTrace(); return null; } return null; }
From source file:edu.mit.scratch.Scratch.java
public static ScratchSession createSession(final String username, String password) throws ScratchLoginException { try {//from w ww .j a v a2s.c o m final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT) // Changed due to deprecation .build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final 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(); resp = httpClient.execute(csrf); resp.close(); String csrfToken = null; for (final Cookie c : cookieStore.getCookies()) if (c.getName().equals("scratchcsrftoken")) csrfToken = c.getValue(); final JSONObject loginObj = new JSONObject(); loginObj.put("username", username); loginObj.put("password", password); loginObj.put("captcha_challenge", ""); loginObj.put("captcha_response", ""); loginObj.put("embed_captcha", false); loginObj.put("timezone", "America/New_York"); loginObj.put("csrfmiddlewaretoken", csrfToken); final HttpUriRequest login = RequestBuilder.post().setUri("https://scratch.mit.edu/accounts/login/") .addHeader("Accept", "application/json, text/javascript, */*; q=0.01") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate").addHeader("Accept-Language", "en-US,en;q=0.8") .addHeader("Content-Type", "application/json").addHeader("X-Requested-With", "XMLHttpRequest") .addHeader("X-CSRFToken", csrfToken).setEntity(new StringEntity(loginObj.toString())).build(); resp = httpClient.execute(login); password = null; 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); final JSONObject jsonOBJ = new JSONObject( result.toString().substring(1, result.toString().length() - 1)); if ((int) jsonOBJ.get("success") != 1) throw new ScratchLoginException(); String ssi = null; String sct = null; String e = null; final Header[] headers = resp.getAllHeaders(); for (final Header header : headers) if (header.getName().equals("Set-Cookie")) { final String value = header.getValue(); final String[] split = value.split(Pattern.quote("; ")); for (final String s : split) { if (s.contains("=")) { final String[] split2 = s.split(Pattern.quote("=")); final String key = split2[0]; final String val = split2[1]; if (key.equals("scratchsessionsid")) ssi = val; else if (key.equals("scratchcsrftoken")) sct = val; else if (key.equals("expires")) e = val; } } } resp.close(); return new ScratchSession(ssi, sct, e, username); } catch (final IOException e) { e.printStackTrace(); throw new ScratchLoginException(); } }
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 ww w .j a va2s . co 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(); } } }