List of usage examples for org.apache.http.impl.client BasicCookieStore addCookie
public synchronized void addCookie(final Cookie cookie)
From source file:zz.pseas.ghost.login.weibo.WeiboLogin.java
public static void main(String[] args) { WebDriver driver = BrowserFactory.getIE(); driver.get("http://weibo.com/"); Set<Cookie> cookies = driver.manage().getCookies(); BasicCookieStore cookieStore = new BasicCookieStore(); for (Cookie c : cookies) { BasicClientCookie c1 = new BasicClientCookie(c.getName(), c.getValue()); c1.setDomain(c.getDomain() == null ? "weibo" : c.getDomain()); c1.setPath(c.getPath());//from w w w . j av a 2 s . c o m Date d = c.getExpiry(); if (d != null) { c1.setExpiryDate(d); } cookieStore.addCookie(c1); } driver.quit(); GhostClient client = new GhostClient("utf-8", cookieStore); String url = "http://weibo.com/p/10080813dc27e2acb1441006674c8aa2ef07d4/followlist?page=1#Pl_Core_F4RightUserList__38"; //HttpGet get = new HttpGet(url); String s = client.get(url); System.out.println(s); String next = StringUtil.regex(s, "(?<=replace\\(\").*?(?=\")"); String html = client.get(next); System.out.println(html); }
From source file:org.alfresco.selenium.FetchHttpClient.java
public static CloseableHttpClient getHttpClient(final WebDriver driver) { BasicCookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(generateSessionCookie(driver)); //Create http client to retrieve the file. return HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); }
From source file:zz.pseas.ghost.utils.DownloadUtil.java
public static CookieStore convertToCookieStore(Set<Cookie> cookies) { BasicCookieStore store = new BasicCookieStore(); for (Cookie c : cookies) { BasicClientCookie c1 = new BasicClientCookie(c.getName(), c.getValue()); c1.setDomain(c.getDomain());/* ww w . j ava2 s .c om*/ c1.setPath(c.getPath()); c1.setExpiryDate(c.getExpiry()); store.addCookie(c1); } return store; }
From source file:com.domuslink.communication.ApiHandler.java
/** * Pull the raw text content of the given URL. This call blocks until the * operation has completed, and is synchronized because it uses a shared * buffer {@link #sBuffer}.// w w w. java 2 s. c o m * * @param type The type of either a GET or POST for the request * @param commandURI The constructed URI for the path * @return The raw content returned by the server. * @throws ApiException If any connection or server error occurs. */ protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler) throws ApiException { HttpResponse response; HttpRequestBase request; if (sUserAgent == null) { throw new ApiException("User-Agent string must be prepared"); } // Create client and set our specific user-agent string DefaultHttpClient client = new DefaultHttpClient(); UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds); client.setCredentialsProvider(credsProvider); CookieStore cookieStore = cookieHandler.getCookieStore(); if (cookieStore != null) { boolean expiredCookies = false; Date nowTime = new Date(); for (Cookie theCookie : cookieStore.getCookies()) { if (theCookie.isExpired(nowTime)) expiredCookies = true; } if (!expiredCookies) client.setCookieStore(cookieStore); else { cookieHandler.setCookieStore(null); cookieStore = null; } } try { if (type == POST_TYPE) request = new HttpPost(commandURI); else request = new HttpGet(commandURI); request.setHeader("User-Agent", sUserAgent); response = client.execute(request); // Check if server response is valid StatusLine status = response.getStatusLine(); if (status.getStatusCode() != HTTP_STATUS_OK) { Log.e(TAG, "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString()); throw new ApiException("Invalid response from server: " + status.toString()); } // Pull content stream from response HttpEntity entity = response.getEntity(); InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } if (cookieStore == null) { List<Cookie> realCookies = client.getCookieStore().getCookies(); if (!realCookies.isEmpty()) { BasicCookieStore newCookies = new BasicCookieStore(); for (int i = 0; i < realCookies.size(); i++) { newCookies.addCookie(realCookies.get(i)); // Log.d(TAG, "aCookie - " + realCookies.get(i).toString()); } cookieHandler.setCookieStore(newCookies); } } // Return result from buffered stream return content.toString(); } catch (IOException e) { Log.e(TAG, "urlContent: client execute: " + commandURI.toString()); throw new ApiException("Problem communicating with API", e); } catch (IllegalArgumentException e) { Log.e(TAG, "urlContent: client execute: " + commandURI.toString()); throw new ApiException("Problem communicating with API", e); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources client.getConnectionManager().shutdown(); } }
From source file:io.vertigo.struts2.FileDownloader4Tests.java
/** * Load in all the cookies WebDriver currently knows about so that we can mimic the browser cookie state * * @param seleniumCookieSet//from w w w.java2 s . co m * @return BasicCookieStore */ private static BasicCookieStore mimicCookieState(final Set<Cookie> seleniumCookieSet) { final BasicCookieStore mimicWebDriverCookieStore = new BasicCookieStore(); for (final Cookie seleniumCookie : seleniumCookieSet) { final BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue()); duplicateCookie.setDomain(seleniumCookie.getDomain()); duplicateCookie.setSecure(seleniumCookie.isSecure()); duplicateCookie.setExpiryDate(seleniumCookie.getExpiry()); duplicateCookie.setPath(seleniumCookie.getPath()); mimicWebDriverCookieStore.addCookie(duplicateCookie); } return mimicWebDriverCookieStore; }
From source file:org.rapidoid.http.HttpClientUtil.java
static CloseableHttpAsyncClient client(HttpClient client) { ConnectionReuseStrategy reuseStrategy = client.reuseConnections() ? new DefaultConnectionReuseStrategy() : new NoConnectionReuseStrategy(); HttpAsyncClientBuilder builder = HttpAsyncClients.custom() .setThreadFactory(new RapidoidThreadFactory("http-client")).disableConnectionState() .disableAuthCaching().setMaxConnPerRoute(client.maxConnPerRoute()) .setMaxConnTotal(client.maxConnTotal()).setConnectionReuseStrategy(reuseStrategy) .setRedirectStrategy(client.followRedirects() ? new DefaultRedirectStrategy() : NO_REDIRECTS); if (!U.isEmpty(client.cookies())) { BasicCookieStore cookieStore = new BasicCookieStore(); for (Map.Entry<String, String> e : client.cookies().entrySet()) { BasicClientCookie cookie = new BasicClientCookie(e.getKey(), e.getValue()); String host = client.host(); U.notNull(host, "HTTP client host"); cookie.setDomain(getDomain(host)); cookie.setPath("/"); cookieStore.addCookie(cookie); }//from w ww.j a v a 2 s . c o m builder = builder.setDefaultCookieStore(cookieStore); } if (client.userAgent() != null) { builder = builder.setUserAgent(client.userAgent()); } if (!client.keepCookies() && U.isEmpty(client.cookies())) { builder = builder.disableCookieManagement(); } return builder.build(); }
From source file:org.coding.git.api.CodingNetConnection.java
private static CookieStore createCookieStore(CodingNetAuthData auth) { BasicCookieStore cookieStore = new BasicCookieStore(); CodingNetAuthData.BasicAuth basicAuth = auth.getBasicAuth(); if (basicAuth != null) { String code = basicAuth.getSid(); if (code != null) { BasicClientCookie cookie = new BasicClientCookie("sid", code); cookie.setDomain(".coding.net"); cookie.setPath("/"); cookie.setSecure(true);/*from w ww. j a va2s . c om*/ cookieStore.addCookie(cookie); } } return cookieStore; }
From source file:ddf.security.samlp.impl.LogoutMessageImpl.java
@Override public String sendSamlLogoutRequest(LogoutRequest request, String targetUri, boolean isSoap, @Nullable Cookie cookie) throws IOException, WSSecurityException { XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage(request) : request; Element requestElement = getElementFromSaml(xmlObject); String requestMessage = DOM2Writer.nodeToString(requestElement); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost post = new HttpPost(targetUri); post.addHeader("Cache-Control", "no-cache, no-store"); post.addHeader("Pragma", "no-cache"); post.addHeader("SOAPAction", SAML_SOAP_ACTION); post.addHeader("Content-Type", "application/soap+xml"); post.setEntity(new StringEntity(requestMessage, "utf-8")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); BasicHttpContext context = new BasicHttpContext(); if (cookie != null) { BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue()); basicClientCookie.setDomain(cookie.getDomain()); basicClientCookie.setPath(cookie.getPath()); BasicCookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(basicClientCookie); context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); }//from w ww.j a va 2 s . co m return httpClient.execute(post, responseHandler, context); } }
From source file:org.jboss.as.test.integration.web.cookie.DefaultCookieVersionTestCase.java
private void commonSendCookieVersion(int cookieVersion) throws IOException, URISyntaxException { configureDefaultCookieVersion(cookieVersion); BasicCookieStore basicCookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("testCookie", "testCookieValue"); cookie.setVersion(cookieVersion);/*from ww w . j av a2 s . c om*/ cookie.setDomain(cookieURL.getHost()); basicCookieStore.addCookie(cookie); try (CloseableHttpClient httpclient = HttpClientBuilder.create().setDefaultCookieStore(basicCookieStore) .build()) { HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieEchoServlet")); if (response.getEntity() != null) { Assert.assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode()); Assert.assertEquals(cookieVersion + "", EntityUtils.toString(response.getEntity())); } } }
From source file:com.farmafene.commons.cas.LoginTGT.java
public void doLogout(Cookie cookie) { HttpResponse res = null;//ww w. ja v a2s. co m HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(getCasServerURL()); DefaultHttpClient client = null; client = f.getClient(); HttpContext localContext = new BasicHttpContext(); BasicCookieStore cs = new BasicCookieStore(); cs.addCookie(cookie); HttpPost post = new HttpPost(getURL("logout")); client.setCookieStore(cs); localContext.setAttribute(ClientContext.COOKIE_STORE, cs); try { res = client.execute(post, localContext); if (res.getStatusLine().getStatusCode() != 200) { AuriusAuthException ex = new AuriusAuthException("Error"); logger.error("Excepcion en el login", ex); throw ex; } } catch (ClientProtocolException e) { AuriusAuthException ex = new AuriusAuthException("ClientProtocolException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } }