Java Code Examples for org.apache.http.impl.client.BasicCookieStore#addCookie()

The following examples show how to use org.apache.http.impl.client.BasicCookieStore#addCookie() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RealmsAPI.java    From FishingBot with GNU General Public License v3.0 6 votes vote down vote up
public RealmsAPI(AuthData authData) {
    BasicCookieStore cookies = new BasicCookieStore();

    BasicClientCookie sidCookie = new BasicClientCookie("sid", String.join(":", "token", authData.getAccessToken(), authData.getProfile()));
    BasicClientCookie userCookie = new BasicClientCookie("user", authData.getUsername());
    BasicClientCookie versionCookie = new BasicClientCookie("version", ProtocolConstants.getVersionString(FishingBot.getInstance().getServerProtocol()));

    sidCookie.setDomain(".pc.realms.minecraft.net");
    userCookie.setDomain(".pc.realms.minecraft.net");
    versionCookie.setDomain(".pc.realms.minecraft.net");

    sidCookie.setPath("/");
    userCookie.setPath("/");
    versionCookie.setPath("/");

    cookies.addCookie(sidCookie);
    cookies.addCookie(userCookie);
    cookies.addCookie(versionCookie);

    client = HttpClientBuilder.create()
            .setDefaultCookieStore(cookies)
            .build();
}
 
Example 2
Source File: HttpClient.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Remove a Cookie by name and path
 *
 * @param name cookie name
 * @param path cookie path
 */
@PublicAtsApi
public void removeCookie( String name, String path ) {

    BasicCookieStore cookieStore = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
    if (cookieStore != null) {

        List<Cookie> cookies = cookieStore.getCookies();
        cookieStore.clear();
        for (Cookie cookie : cookies) {
            if (!cookie.getName().equals(name) || !cookie.getPath().equals(path)) {
                cookieStore.addCookie(cookie);
            }
        }
    }
}
 
Example 3
Source File: CSDNLoginApater.java    From crawler-jsoup-maven with Apache License 2.0 6 votes vote down vote up
public static void setCookieStore(HttpResponse httpResponse) {
  System.out.println("----setCookieStore");
  cookieStore = new BasicCookieStore();
  // JSESSIONID
  String setCookie = httpResponse.getFirstHeader("Set-Cookie")
      .getValue();
  String JSESSIONID = setCookie.substring("JSESSIONID=".length(),
      setCookie.indexOf(";"));
  System.out.println("JSESSIONID:" + JSESSIONID);
  // 新建一个Cookie
  BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",
      JSESSIONID);
  cookie.setVersion(0);
  //cookie.setDomain("127.0.0.1");
  //cookie.setPath("/CwlProClient");
  // cookie.setAttribute(ClientCookie.VERSION_ATTR, "0");
  // cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "127.0.0.1");
  // cookie.setAttribute(ClientCookie.PORT_ATTR, "8080");
  // cookie.setAttribute(ClientCookie.PATH_ATTR, "/CwlProWeb");
  cookieStore.addCookie(cookie);
}
 
Example 4
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Authentication with google account
 * @param cookies cookies list keys from google auth
 * @param login username associated to zds login
 * @param id user id on ZdS associated to login
 */
public void authToGoogle(List<HttpCookie> cookies, String login, String id) {
    if(login != null && id != null) {
        this.login = login;
        this.idUser = id;
        log.info("L'identifiant de l'utilisateur " + this.login + " est : " + idUser);
        cookieStore = new BasicCookieStore();
        for(HttpCookie cookie:cookies) {
            BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue());
            c.setDomain(cookie.getDomain());
            c.setPath(cookie.getPath());
            c.setSecure(cookie.getSecure());
            c.setVersion(cookie.getVersion());
            c.setComment(cookie.getComment());
            cookieStore.addCookie(c);
        }
        context.setCookieStore(cookieStore);
        this.authenticated = true;
    }
    else {
        log.debug("Le login de l'utilisateur n'a pas pu être trouvé");
    }
}
 
Example 5
Source File: DefaultCookieManager.java    From esigate with Apache License 2.0 6 votes vote down vote up
@Override
public List<Cookie> getCookies(DriverRequest originalRequest) {
    BasicCookieStore cookies = new BasicCookieStore();
    UserContext userContext = originalRequest.getUserContext();

    // Read cookies from session
    BasicCookieStore sessionCookies = (BasicCookieStore) userContext.getAttribute(COOKIES_LIST_SESSION_KEY);
    if (sessionCookies != null) {
        for (Cookie c : sessionCookies.getCookies()) {
            cookies.addCookie(c);
        }
    }

    // Read cookie from request
    Cookie[] requestCookies = originalRequest.getOriginalRequest().getCookies();
    if (requestCookies != null) {
        for (Cookie cookie : requestCookies) {
            String name = cookie.getName();
            if (!storeCookiesInSession.contains(name) && !storeCookiesInSession.contains("*")
                    && !discardCookies.contains(name) && !discardCookies.contains("*")) {
                cookies.addCookie(rewriteForServer(cookie, originalRequest));
            }
        }
    }
    return cookies.getCookies();
}
 
Example 6
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
    cookie.setDomain(COOKIE_DOMAIN);
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
    final HttpGet request = new HttpGet(HOST_WITH_COOKIE);

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    final Future<HttpResponse> future = client.execute(request, localContext, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example 7
Source File: HttpClientCookieLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public final void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    instance = HttpClientBuilder.create().build();

    final HttpGet request = new HttpGet("http://www.github.com");

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
    response = instance.execute(request, localContext);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example 8
Source File: FileDownloader.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 5 votes vote down vote up
private BasicCookieStore getWebDriverCookies(Set<Cookie> seleniumCookieSet) {
    BasicCookieStore copyOfWebDriverCookieStore = new BasicCookieStore();
    for (Cookie seleniumCookie : seleniumCookieSet) {
        BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
        duplicateCookie.setDomain(seleniumCookie.getDomain());
        duplicateCookie.setSecure(seleniumCookie.isSecure());
        duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
        duplicateCookie.setPath(seleniumCookie.getPath());
        copyOfWebDriverCookieStore.addCookie(duplicateCookie);
    }

    return copyOfWebDriverCookieStore;
}
 
Example 9
Source File: FileDownloader.java    From Mastering-Selenium-WebDriver-3.0-Second-Edition with MIT License 5 votes vote down vote up
private BasicCookieStore getWebDriverCookies(Set<Cookie> seleniumCookieSet) {
    BasicCookieStore copyOfWebDriverCookieStore = new BasicCookieStore();
    for (Cookie seleniumCookie : seleniumCookieSet) {
        BasicClientCookie duplicateCookie = new BasicClientCookie(seleniumCookie.getName(), seleniumCookie.getValue());
        duplicateCookie.setDomain(seleniumCookie.getDomain());
        duplicateCookie.setSecure(seleniumCookie.isSecure());
        duplicateCookie.setExpiryDate(seleniumCookie.getExpiry());
        duplicateCookie.setPath(seleniumCookie.getPath());
        copyOfWebDriverCookieStore.addCookie(duplicateCookie);
    }

    return copyOfWebDriverCookieStore;
}
 
Example 10
Source File: TokenServiceHttpsJwt.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
private BasicCookieStore prepareCookieWithToken(String jwtToken) {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie(COOKIE_PREFIX, jwtToken);
    cookie.setDomain(host);
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    return cookieStore;
}
 
Example 11
Source File: CloseableClientProviderTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testGetHttpClientWithTrustStoreWithCookies() throws ZaasConfigurationException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("apimlAuthenticationToken", "token");
    cookie.setDomain(configProperties.getApimlHost());
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    assertNotNull(httpsClientProvider.getHttpsClientWithTrustStore(cookieStore));
}
 
Example 12
Source File: BitShareAccount.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
private void initialize() throws Exception {
    httpContext = new BasicHttpContext();
    cookieStore = new BasicCookieStore();
    httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    
    //Force to use en language
    BasicClientCookie cookie = new BasicClientCookie("language_selection", "EN");
    cookie.setDomain(".bitshare.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    //NULogger.getLogger().info("Getting startup cookies & link from BitShare.com");
    //responseString = NUHttpClientUtils.getData("http://bitshare.com", httpContext);
}
 
Example 13
Source File: HttpClientCookieLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    final HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    final HttpGet request = new HttpGet("http://www.github.com");

    response = (CloseableHttpResponse) client.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example 14
Source File: HttpClientCookieLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public final void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() throws IOException {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    instance = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    final HttpGet request = new HttpGet("http://www.github.com");

    response = instance.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}
 
Example 15
Source File: FetchDataTest.java    From BUbiNG with Apache License 2.0 4 votes vote down vote up
@Test
public void testSyncWithCookies() throws IOException, NoSuchAlgorithmException, IllegalArgumentException {
	final URI url0 = BURL.parse(new MutableString("http://foo.bar/goo/first.html"));
	final URI url1 = BURL.parse(new MutableString("http://foo.bar/goo/second.html"));
	final String content0 = "";
	final String content1 = "";

	proxy = new SimpleFixedHttpProxy(true);

	proxy.add200(url0, "Set-cookie: cookie=hello; Domain: foo.bar", content0);
	proxy.add200(url1, "", content1);

	proxy.start();

	FetchData fetchData = new FetchData(testConfiguration);

	BasicCookieStore cookieStore = new BasicCookieStore();
	HttpClient httpClient = getHttpClient(new HttpHost("localhost", proxy.port()), false, cookieStore);

	// This shows we do receive cookies
	fetchData.fetch(url0, httpClient, null, null, false);
	Cookie[] cookie = FetchingThread.getCookies(url0, cookieStore, testConfiguration.cookieMaxByteSize);
	assertEquals("cookie", cookie[0].getName());
	assertEquals("hello", cookie[0].getValue());

	// This shows we do send cookies
	// First attempt: sending back the same cookies just received
	fetchData.fetch(url1, httpClient, null, null, false);
	assertTrue(IOUtils.toString(fetchData.response().getEntity().getContent(), Charsets.ISO_8859_1).contains("hello"));
	// Second attempt: sending new cookies
	cookieStore.clear();
	BasicClientCookie clientCookie = new BasicClientCookie("returned", "cookie");
	clientCookie.setDomain("foo.bar");
	cookieStore.addCookie(clientCookie);
	fetchData.fetch(url1, httpClient, null, null, false);
	assertTrue(IOUtils.toString(fetchData.response().getEntity().getContent(), Charsets.ISO_8859_1).contains("returned"));

	// This shows we do not send undue cookies
	cookieStore.clear();
	clientCookie.setDomain("another.domain");
	cookieStore.addCookie(clientCookie);
	fetchData.fetch(url1, httpClient, null, null, false);
	assertFalse(IOUtils.toString(fetchData.response().getEntity().getContent(), Charsets.ISO_8859_1).contains("returned"));

	System.out.println(Arrays.toString(FetchingThread.getCookies(url1, cookieStore, testConfiguration.cookieMaxByteSize)));

	fetchData.close();
}
 
Example 16
Source File: DemoServletsAdapterTest.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Test
public void testTokenConcurrentRefresh() {
    RealmResource demoRealm = adminClient.realm("demo");
    RealmRepresentation demo = demoRealm.toRepresentation();

    demo.setAccessTokenLifespan(2);
    demo.setRevokeRefreshToken(true);
    demo.setRefreshTokenMaxReuse(0);

    demoRealm.update(demo);

    // Login
    tokenRefreshPage.navigateTo();
    assertTrue(testRealmLoginPage.form().isUsernamePresent());
    assertCurrentUrlStartsWithLoginUrlOf(testRealmPage);
    testRealmLoginPage.form().login("[email protected]", "password");
    assertCurrentUrlEquals(tokenRefreshPage);

    setAdapterAndServerTimeOffset(5, tokenRefreshPage.toString());

    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie jsessionid = new BasicClientCookie("JSESSIONID", driver.manage().getCookieNamed("JSESSIONID").getValue());

    jsessionid.setDomain("localhost");
    jsessionid.setPath("/");
    cookieStore.addCookie(jsessionid);

    ExecutorService executor = Executors.newWorkStealingPool();
    CompletableFuture future = CompletableFuture.completedFuture(null);

    try {
        for (int i = 0; i < 5; i++) {
            future = CompletableFuture.allOf(future, CompletableFuture.runAsync(() -> {
                try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore)
                        .build()) {
                    HttpUriRequest request = new HttpGet(tokenRefreshPage.getInjectedUrl().toString());
                    try (CloseableHttpResponse httpResponse = client.execute(request)) {
                        assertTrue("Token not refreshed", EntityUtils.toString(httpResponse.getEntity()).contains("accessToken"));
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }, executor));
        }
        
        future.join();
    } finally {
        executor.shutdownNow();
    }

    // Revert times
    setAdapterAndServerTimeOffset(0, tokenRefreshPage.toString());
}