Java Code Examples for org.apache.http.client.CookieStore#getCookies()

The following examples show how to use org.apache.http.client.CookieStore#getCookies() . 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: CookieManagerTests.java    From vividus with Apache License 2.0 6 votes vote down vote up
@Test
void testGetCookiesAsHttpCookieStore()
{
    configureMockedWebDriver();
    Cookie seleniumCookie = createSeleniumCookie();
    mockGetCookies(seleniumCookie);
    CookieStore cookieStore = cookieManager.getCookiesAsHttpCookieStore();
    List<org.apache.http.cookie.Cookie> resultCookies = cookieStore.getCookies();
    assertEquals(1, resultCookies.size());
    org.apache.http.cookie.Cookie httpCookie = resultCookies.get(0);
    assertThat(httpCookie, instanceOf(BasicClientCookie.class));
    BasicClientCookie clientCookie = (BasicClientCookie) httpCookie;
    assertAll(
        () -> assertEquals(seleniumCookie.getDomain(), clientCookie.getDomain()),
        () -> assertEquals(seleniumCookie.getExpiry(), clientCookie.getExpiryDate()),
        () -> assertEquals(seleniumCookie.getName(), clientCookie.getName()),
        () -> assertEquals(seleniumCookie.getPath(), clientCookie.getPath()),
        () -> assertEquals(seleniumCookie.getValue(), clientCookie.getValue()),
        () -> assertEquals(seleniumCookie.isSecure(), clientCookie.isSecure()),
        () -> assertEquals(seleniumCookie.getDomain(), clientCookie.getAttribute(ClientCookie.DOMAIN_ATTR)),
        () -> assertEquals(seleniumCookie.getPath(), clientCookie.getAttribute(ClientCookie.PATH_ATTR))
    );
}
 
Example 2
Source File: SimpleHttpFetcherTest.java    From ache with Apache License 2.0 6 votes vote down vote up
@Test
public void testCookieStore() {
    Cookie cookie = new Cookie("key1", "value1");
    cookie.setDomain(".slides.com");

    HashMap<String, List<Cookie>> map = new HashMap<>();
    List<Cookie> listOfCookies = new ArrayList<>();
    listOfCookies.add(cookie);
    map.put("www.slides.com", listOfCookies);

    SimpleHttpFetcher baseFetcher =
            FetcherFactory.createSimpleHttpFetcher(new HttpDownloaderConfig());
    CookieUtils.addCookies(map, baseFetcher);

    CookieStore globalCookieStore = baseFetcher.getCookieStore();
    List<org.apache.http.cookie.Cookie> resultList = globalCookieStore.getCookies();
    assertTrue(resultList.get(0).getName().equals("key1"));
    assertTrue(resultList.get(0).getValue().equals("value1"));
    assertTrue(resultList.get(0).getDomain().equals("slides.com"));
}
 
Example 3
Source File: FetchingThread.java    From BUbiNG with Apache License 2.0 6 votes vote down vote up
/** Returns the list of cookies in a given store in the form of an array, limiting their overall size
 * (only the maximal prefix of cookies satisfying the size limit is returned). Note that the size limit is expressed
 * in bytes, but the actual memory footprint is larger because of object overheads and because strings
 * are made of 16-bits characters. Moreover, cookie attributes are not measured when evaluating size.
 *
 * @param url the URL which generated the cookies (for logging purposes).
 * @param cookieStore a cookie store, usually generated by a response.
 * @param cookieMaxByteSize the maximum overall size of cookies in bytes.
 * @return the list of cookies in a given store in the form of an array, with limited overall size.
 */
public static Cookie[] getCookies(final URI url, final CookieStore cookieStore, final int cookieMaxByteSize) {
	int overallLength = 0, i = 0;
	final List<Cookie> cookies = cookieStore.getCookies();
	for (final Cookie cookie : cookies) {
		/* Just an approximation, and doesn't take attributes into account, but
		 * there is no way to enumerate the attributes of a cookie. */
		overallLength += length(cookie.getName());
		overallLength += length(cookie.getValue());
		overallLength += length(cookie.getDomain());
		overallLength += length(cookie.getPath());
		if (overallLength > cookieMaxByteSize) {
			LOGGER.warn("URL " + url + " returned too large cookies (" + overallLength + " characters)");
			return cookies.subList(0, i).toArray(new Cookie[i]);
		}
		i++;
	}
	return cookies.toArray(new Cookie[cookies.size()]);
}
 
Example 4
Source File: CookieFactory.java    From bitherj with Apache License 2.0 6 votes vote down vote up
public synchronized static boolean initCookie() {
    boolean success = true;
    isRunning = true;
    CookieStore cookieStore = AbstractApp.bitherjSetting.getCookieStore();
    if (cookieStore.getCookies() == null
            || cookieStore.getCookies().size() == 0) {
        try {
            GetCookieApi getCookieApi = new GetCookieApi();
            getCookieApi.handleHttpPost();
            // log.debug("getCookieApi");
        } catch (Exception e) {
            success = false;
            e.printStackTrace();
        }
    }
    isRunning = false;
    return success;

}
 
Example 5
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a cookie value from the name.
 * @param httpContext HttpContext in which the cookies store.
 * @param name the name of the cookie.
 * @return the value of the cookie.
 */
public static String getCookieValue(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        if(cookieName.contains(name)){
            return cookies.get(i).getValue();
        }
    }
    return null;
}
 
Example 6
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a cookie from the name.
 * @param httpContext HttpContext in which the cookies store.
 * @param name the name of the cookie.
 * @return the Cookie object.
 */
public static Cookie getCookie(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    Cookie cookie;
    for(int i = 0; i < cookies.size(); i++){
        cookie = cookies.get(i);
        cookieName = cookie.getName();
        if(cookieName.contains(name)){
            return cookie;
        }
    }
    return null;
}
 
Example 7
Source File: NUHttpClient.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Delete all the cookie given the domain domain.
 * @param domain the domain name.
 */
public static void deleteCookies(String domain) {
    CookieStore cookieStore = httpClient.getCookieStore();
    CookieStore newCookieStore = new BasicCookieStore();
    List<Cookie> cookies = cookieStore.getCookies();
    for(int i = 0; i < cookies.size(); i++){
        if(!cookies.get(i).getDomain().contains(domain)){
            newCookieStore.addCookie(cookies.get(i));
        }
    }
    
    //Set the new cookie store
    httpClient.setCookieStore(newCookieStore);
}
 
Example 8
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * There is a cookie that starts with this name?
 * @param httpContext the context.
 * @param name the first part of the name of the cookie.
 * @return boolean value.
 */
public static boolean existCookieStartWithValue(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        if(cookieName.startsWith(name)){
            return true;
        }
    }
    return false;
}
 
Example 9
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a cookie value from the exact name.
 * @param httpContext HttpContext in which the cookies store.
 * @param name the name of the cookie.
 * @return the value of the cookie.
 */
public static String getCookieValueWithExactName(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        if(cookieName.equals(name)){
            return cookies.get(i).getValue();
        }
    }
    return null;
}
 
Example 10
Source File: CookieStoreUT.java    From clouddisk with MIT License 5 votes vote down vote up
public String readCookieValueForDisk(final String filter) {
	final CookieStore cookieStore = readCookieStoreForDisk(new String[] { filter });
	final List<Cookie> cookies = cookieStore.getCookies();
	for (final Cookie cookie : cookies) {
		if (cookie.getName().equals(filter)) {
			return cookie.getValue();
		}
	}
	return null;
}
 
Example 11
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get a cookie value from the name. If the cookie starts with the name, you'll get this value.
 * @param httpContext HttpContext in which the cookies store
 * @param name the first part of the name of the cookie.
 * @return the String cookie.
 */
public static String getCookieStartsWithValue(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        if(cookieName.startsWith(name)){
            return cookies.get(i).getValue();
        }
    }
    return null;
}
 
Example 12
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * There is a cookie with this name?
 * @param httpContext the context.
 * @param name the name of the cookie.
 * @return boolean value.
 */
public static boolean existCookie(HttpContext httpContext, String name){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    String cookieName;
    for(int i = 0; i < cookies.size(); i++){
        cookieName = cookies.get(i).getName();
        if(cookieName.contains(name)){
            return true;
        }
    }
    return false;
}
 
Example 13
Source File: ZdsHttp.java    From zest-writer with GNU General Public License v3.0 5 votes vote down vote up
private String getCookieValue(CookieStore cookieStore, String cookieName) {
    String value = null;
    for (Cookie cookie : cookieStore.getCookies()) {

        if (cookie.getName().equals(cookieName)) {
            value = cookie.getValue();
        }
    }
    return value;
}
 
Example 14
Source File: AsyncClientCustomContext.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	try {
		// Create a local instance of cookie store
		CookieStore cookieStore = new BasicCookieStore();

		// Create local HTTP context
		HttpClientContext localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);

           HttpGet httpget = new HttpGet("http://localhost/");
		System.out.println("Executing request " + httpget.getRequestLine());

		httpclient.start();

		// Pass local context as a parameter
		Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

		// Please note that it may be unsafe to access HttpContext instance
		// while the request is still being executed

		HttpResponse response = future.get();
		System.out.println("Response: " + response.getStatusLine());
		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			System.out.println("Local cookie: " + cookies.get(i));
		}
		System.out.println("Shutting down");
	} finally {
		httpclient.close();
	}
}
 
Example 15
Source File: FormAuthCookiesTestCase.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private String getCredentialCookie(CookieStore cookieStore) {
    for (Cookie cookie : cookieStore.getCookies()) {
        if ("laitnederc-sukrauq".equals(cookie.getName())) {
            return cookie.getValue();
        }
    }
    return null;
}
 
Example 16
Source File: HttpTest.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
/**
 * @return name->value of cookies in the cookie store.
 */
public Map<String, String> cookieValues() {
    Map<String, String> result = null;
    CookieStore cookies = getResponse().getCookieStore();
    if (cookies != null) {
        result = new LinkedHashMap<>();
        for (Cookie cookie : cookies.getCookies()) {
            result.put(cookie.getName(), cookie.getValue());
        }
    }
    return result;
}
 
Example 17
Source File: CookieUtils.java    From neembuu-uploader with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Print all the cookie in the context (for debug).
 * @param httpContext HttpContext in which the cookies store
 * 
 */
public static void printCookie(HttpContext httpContext){
    CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
    List<Cookie> cookies = cookieStore.getCookies();
    for(int i = 0; i < cookies.size(); i++){
        NULogger.getLogger().log(Level.INFO, "{0}: {1}",  new Object[]{cookies.get(i).getName(), cookies.get(i).getValue()});
    }
}
 
Example 18
Source File: Sina.java    From FreeServer with Apache License 2.0 5 votes vote down vote up
/**
 * 获取新浪单点登录cookie
 * @param info
 * @return
 * @throws IOException
 */
public static String getSinaCookie(UserInfo info) throws IOException {
    CookieStore cookieStore = new BasicCookieStore();
    HttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(ParamUtil.getSinaLogin(info.getBlogUser(), info.getBlogPass()));
    HttpUtil.getPostRes(httpClient,UrlUtil.SINA_LOGIN,entity, ParamUtil.getPubHeader(""));
    String cookieStr = "";
    List<Cookie> cookies = cookieStore.getCookies();
    for (Cookie cookie : cookies) {
        cookieStr += cookie.getName()+"="+cookie.getValue()+";";
    }
    return cookieStr;
}
 
Example 19
Source File: CookieUtils.java    From BigApp_Discuz_Android with Apache License 2.0 4 votes vote down vote up
public static List<Cookie>  getCookies(Context context) {

        CookieStore cookieStore = com.youzu.clan.base.net.CookieManager.getInstance().getCookieStore(context);
        List<Cookie> cookies = cookieStore.getCookies();
        return cookies;
    }
 
Example 20
Source File: ApiRequest.java    From Kingdee-K3Cloud-Web-Api with GNU General Public License v3.0 4 votes vote down vote up
public void doPost() {
    HttpPost httpPost = getHttpPost();
    try {
        if (httpPost == null) {
            return;
        }

        httpPost.setEntity(getServiceParameters().toEncodeFormEntity());
        this._response = getHttpClient().execute(httpPost);

        if (this._response.getStatusLine().getStatusCode() == 200) {
            HttpEntity respEntity = this._response.getEntity();

            if (this._currentsessionid == "") {
                CookieStore mCookieStore = ((AbstractHttpClient) getHttpClient())
                        .getCookieStore();
                List cookies = mCookieStore.getCookies();
                if (cookies.size() > 0) {
                    this._cookieStore = mCookieStore;
                }
                for (int i = 0; i < cookies.size(); i++) {
                    if (_aspnetsessionkey.equals(((Cookie) cookies.get(i)).getName())) {
                        this._aspnetsessionid = ((Cookie) cookies.get(i)).getValue();
                    }

                    if (_sessionkey.equals(((Cookie) cookies.get(i)).getName())) {
                        this._currentsessionid = ((Cookie) cookies.get(i)).getValue();
                    }
                }

            }

            this._responseStream = respEntity.getContent();
            this._responseString = streamToString(this._responseStream);

            if (this._isAsynchronous.booleanValue()) {
                this._listener.onRequsetSuccess(this);
            }
        }
    } catch (Exception e) {
        if (this._isAsynchronous.booleanValue()) {
            this._listener.onRequsetError(this, e);
        }
    } finally {
        if (httpPost != null) {
            httpPost.abort();
        }
    }
}