当前位置: 首页>>代码示例>>Java>>正文


Java CookieStore类代码示例

本文整理汇总了Java中org.apache.http.client.CookieStore的典型用法代码示例。如果您正苦于以下问题:Java CookieStore类的具体用法?Java CookieStore怎么用?Java CookieStore使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


CookieStore类属于org.apache.http.client包,在下文中一共展示了CookieStore类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: HttpResult

import org.apache.http.client.CookieStore; //导入依赖的package包/类
public HttpResult(HttpResponse httpResponse, CookieStore cookieStore) {
	if (cookieStore != null) {
		this.cookies = cookieStore.getCookies().toArray(new Cookie[0]);
	}

	if (httpResponse != null) {
		this.headers = httpResponse.getAllHeaders();
		this.statuCode = httpResponse.getStatusLine().getStatusCode();
		if(d)System.out.println(this.statuCode);
		try {
			this.response = EntityUtils.toByteArray(httpResponse
					.getEntity());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
 
开发者ID:Evan-Galvin,项目名称:FreeStreams-TVLauncher,代码行数:19,代码来源:HttpResult.java

示例2: fillSession

import org.apache.http.client.CookieStore; //导入依赖的package包/类
/**
 * 将登录结果保存到给定会话对象中,并激活给定会话对象。
 * @param session 会话对象
 * @throws IllegalStateException 登录未成功时抛出
 * @throws NetworkException 在发生网络问题时抛出
 */
public void fillSession(Session session) throws BiliLiveException {
    try {
        if (status != SUCCESS) throw new IllegalStateException("Bad status: " + status);

        Set<Cookie> cookies = webClient.getCookieManager().getCookies();

        CookieStore store = session.getCookieStore();
        store.clear();
        for (Cookie cookie : cookies) {
            store.addCookie(cookie.toHttpClient()); // HtmlUnit Cookie to HttpClient Cookie
        }

        if (getStatus() == SUCCESS) session.activate();
    } catch (IOException ex) {
        throw new NetworkException("IO Exception", ex);
    }
}
 
开发者ID:cqjjjzr,项目名称:BiliLiveLib,代码行数:24,代码来源:SessionLoginHelper.java

示例3: execute

import org.apache.http.client.CookieStore; //导入依赖的package包/类
public <T> Response<T> execute() {
    HttpProxy httpProxy = getHttpProxyFromPool();
    CookieStore cookieStore = getCookieStoreFromPool();

    CloseableHttpClient httpClient = httpClientPool.getHttpClient(siteConfig, request);
    HttpUriRequest httpRequest = httpClientPool.createHttpUriRequest(siteConfig, request, createHttpHost(httpProxy));
    CloseableHttpResponse httpResponse = null;
    IOException executeException = null;
    try {
        HttpContext httpContext = createHttpContext(httpProxy, cookieStore);
        httpResponse = httpClient.execute(httpRequest, httpContext);
    } catch (IOException e) {
        executeException = e;
    }

    Response<T> response = ResponseFactory.createResponse(
            request.getResponseType(), siteConfig.getCharset(request.getUrl()));

    response.handleHttpResponse(httpResponse, executeException);

    return response;
}
 
开发者ID:brucezee,项目名称:jspider,代码行数:23,代码来源:HttpClientExecutor.java

示例4: getuCookie

import org.apache.http.client.CookieStore; //导入依赖的package包/类
public static CookieStore getuCookie() {
    CookieStore uCookie = new BasicCookieStore();
    try {
        String COOKIE_S_LINKDATA = LemallPlatform.getInstance().getCookieLinkdata();
        if (!TextUtils.isEmpty(COOKIE_S_LINKDATA)) {
            String[] cookies = COOKIE_S_LINKDATA.split("&");
            for (String item : cookies) {
                String[] keyValue = item.split(SearchCriteria.EQ);
                if (keyValue.length == 2) {
                    if (OtherUtil.isContainsChinese(keyValue[1])) {
                        keyValue[1] = URLEncoder.encode(keyValue[1], "UTF-8");
                    }
                    BasicClientCookie cookie = new BasicClientCookie(keyValue[0], keyValue[1]);
                    cookie.setVersion(0);
                    cookie.setDomain(".lemall.com");
                    cookie.setPath("/");
                    uCookie.addCookie(cookie);
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return uCookie;
}
 
开发者ID:JackChan1999,项目名称:letv,代码行数:26,代码来源:AsyncHttpClient.java

示例5: open

import org.apache.http.client.CookieStore; //导入依赖的package包/类
/**
 * Open the entry page.
 *
 * @param retryTimes retry times of qr scan
 */
void open(int retryTimes) {
    final String url = WECHAT_URL_ENTRY;
    HttpHeaders customHeader = new HttpHeaders();
    customHeader.setPragma("no-cache");
    customHeader.setCacheControl("no-cache");
    customHeader.set("Upgrade-Insecure-Requests", "1");
    customHeader.set(HttpHeaders.ACCEPT, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8");
    HeaderUtils.assign(customHeader, getHeader);
    restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(customHeader), String.class);
    //manually insert two cookies into cookiestore, as they're supposed to be stored in browsers by javascript.
    CookieStore store = (CookieStore) ((StatefullRestTemplate) restTemplate).getHttpContext().getAttribute(HttpClientContext.COOKIE_STORE);
    Date maxDate = new Date(Long.MAX_VALUE);
    String domain = WECHAT_URL_ENTRY.replaceAll("https://", "").replaceAll("/", "");
    Map<String, String> cookies = new HashMap<>(3);
    cookies.put("MM_WX_NOTIFY_STATE", "1");
    cookies.put("MM_WX_SOUND_STATE", "1");
    if (retryTimes > 0) {
        cookies.put("refreshTimes", String.valueOf(retryTimes));
    }
    appendAdditionalCookies(store, cookies, domain, "/", maxDate);
    //It's now at entry page.
    this.originValue = WECHAT_URL_ENTRY;
    this.refererValue = WECHAT_URL_ENTRY.replaceAll("/$", "");
}
 
开发者ID:kanjielu,项目名称:jeeves,代码行数:30,代码来源:WechatHttpServiceInternal.java

示例6: init

import org.apache.http.client.CookieStore; //导入依赖的package包/类
/**
 * Initialization
 *
 * @param hostUrl     hostUrl
 * @param baseRequest baseRequest
 * @return current user's information and contact information
 * @throws IOException if the http response body can't be convert to {@link InitResponse}
 */
InitResponse init(String hostUrl, BaseRequest baseRequest) throws IOException {
    String url = String.format(WECHAT_URL_INIT, hostUrl, RandomUtils.generateDateWithBitwiseNot());

    CookieStore store = (CookieStore) ((StatefullRestTemplate) restTemplate).getHttpContext().getAttribute(HttpClientContext.COOKIE_STORE);
    Date maxDate = new Date(Long.MAX_VALUE);
    String domain = hostUrl.replaceAll("https://", "").replaceAll("/", "");
    Map<String, String> cookies = new HashMap<>(3);
    cookies.put("MM_WX_NOTIFY_STATE", "1");
    cookies.put("MM_WX_SOUND_STATE", "1");
    appendAdditionalCookies(store, cookies, domain, "/", maxDate);
    InitRequest request = new InitRequest();
    request.setBaseRequest(baseRequest);
    HttpHeaders customHeader = new HttpHeaders();
    customHeader.set(HttpHeaders.REFERER, hostUrl + "/");
    customHeader.setOrigin(hostUrl);
    HeaderUtils.assign(customHeader, postHeader);
    ResponseEntity<String> responseEntity
            = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request, customHeader), String.class);
    return jsonMapper.readValue(WechatUtils.textDecode(responseEntity.getBody()), InitResponse.class);
}
 
开发者ID:kanjielu,项目名称:jeeves,代码行数:29,代码来源:WechatHttpServiceInternal.java

示例7: getCookies

import org.apache.http.client.CookieStore; //导入依赖的package包/类
/** 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 (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()]);
}
 
开发者ID:LAW-Unimi,项目名称:BUbiNG,代码行数:29,代码来源:FetchingThread.java

示例8: HttpTransportClient

import org.apache.http.client.CookieStore; //导入依赖的package包/类
public HttpTransportClient(int retryAttemptsNetworkErrorCount, int retryAttemptsInvalidStatusCount) {
    this.retryAttemptsNetworkErrorCount = retryAttemptsNetworkErrorCount;
    this.retryAttemptsInvalidStatusCount = retryAttemptsInvalidStatusCount;

    CookieStore cookieStore = new BasicCookieStore();
    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(SOCKET_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS)
            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();

    connectionManager.setMaxTotal(MAX_SIMULTANEOUS_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_SIMULTANEOUS_CONNECTIONS);

    httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            .setDefaultCookieStore(cookieStore)
            .setUserAgent(USER_AGENT)
            .build();
}
 
开发者ID:VKCOM,项目名称:vk-java-sdk,代码行数:25,代码来源:HttpTransportClient.java

示例9: authenticate

import org.apache.http.client.CookieStore; //导入依赖的package包/类
@SuppressWarnings("unchecked")
public boolean authenticate() throws IOException {
	Map<String, Object> body = new LinkedHashMap<>();
	body.putAll(user);
	body.put("extended_login", false);
	HttpEntity entity = new StringEntity(JsonUtils.toJson(body), ContentType.APPLICATION_JSON);
	String resp = httpsClient.post(StringUtils.fillUrl(BASE_LOGIN_URL, params), headerList.toArray(new Header[]{}), entity);
	CookieStore cookieStore = httpsClient.getCookieStore();
	httpsClient.saveCookies(COOKIE_DIR, md5, cookieStore);
	Map<String, Object> respMap = (Map<String, Object>) JsonUtils.fromJson(resp, Map.class);
	if (null != respMap && !respMap.containsKey("error")) {
		data.putAll(respMap);
		webservices = (Map<String, Object>) data.get("webservices");
		Map<String, Object> dsInfo = (Map<String, Object>) data.get("dsInfo");
		params.put("dsid", dsInfo.get("dsid").toString());
		LOG.info("Authentication Completed Successfully");
		authenticate = true;
		return true;
	} else {
		LOG.error("Authentication Fail");
		authenticate = false;
		return false;
	}
}
 
开发者ID:Saisimon,项目名称:tip,代码行数:25,代码来源:ICloud.java

示例10: testFailover

import org.apache.http.client.CookieStore; //导入依赖的package包/类
@Test(timeout = 80000)
public void testFailover() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    String value = executeRequest("read", SERVER_PORT_1, cookieStore);
    assertEquals("null", value);

    executeRequest("write", SERVER_PORT_1, cookieStore);

    instance1.stop();

    HazelcastInstance hzInstance1 = Hazelcast.getHazelcastInstanceByName("hzInstance1");
    if (hzInstance1 != null) {
        hzInstance1.shutdown();
    }

    value = executeRequest("read", SERVER_PORT_2, cookieStore);
    assertEquals("value", value);
}
 
开发者ID:hazelcast,项目名称:hazelcast-tomcat-sessionmanager,代码行数:19,代码来源:AbstractStickySessionsTest.java

示例11: InternalHttpClient

import org.apache.http.client.CookieStore; //导入依赖的package包/类
public InternalHttpClient(
        final ClientExecChain execChain,
        final HttpClientConnectionManager connManager,
        final HttpRoutePlanner routePlanner,
        final Lookup<CookieSpecProvider> cookieSpecRegistry,
        final Lookup<AuthSchemeProvider> authSchemeRegistry,
        final CookieStore cookieStore,
        final CredentialsProvider credentialsProvider,
        final RequestConfig defaultConfig,
        final List<Closeable> closeables) {
    super();
    Args.notNull(execChain, "HTTP client exec chain");
    Args.notNull(connManager, "HTTP connection manager");
    Args.notNull(routePlanner, "HTTP route planner");
    this.execChain = execChain;
    this.connManager = connManager;
    this.routePlanner = routePlanner;
    this.cookieSpecRegistry = cookieSpecRegistry;
    this.authSchemeRegistry = authSchemeRegistry;
    this.cookieStore = cookieStore;
    this.credentialsProvider = credentialsProvider;
    this.defaultConfig = defaultConfig;
    this.closeables = closeables;
}
 
开发者ID:xxonehjh,项目名称:remote-files-sync,代码行数:25,代码来源:InternalHttpClient.java

示例12: printCookieStore

import org.apache.http.client.CookieStore; //导入依赖的package包/类
public static void printCookieStore(CookieStore cookieStore) {
    List<Cookie> cookies = cookieStore.getCookies();
    Log.e("APP", "========================================== start cookies.size:" + cookies.size());
    if (!cookies.isEmpty()) {
        for (int i = 0; i < cookies.size(); i++) {
            Cookie ck = cookies.get(i);
            String ckstr = ck.getName() + "=" + ck.getValue() + ";"
                    + "expiry=" + ck.getExpiryDate() + ";"
                    + "domain=" + ck.getDomain() + ";"
                    + "path=/";

            Log.v("APP", "cookieStr:" + ckstr);
        }
    }
    Log.e("APP", "========================================== end cookies.size:" + cookies.size());
}
 
开发者ID:BigAppOS,项目名称:BigApp_Discuz_Android,代码行数:17,代码来源:ClanBaseUtils.java

示例13: testExecuteLocalContext

import org.apache.http.client.CookieStore; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testExecuteLocalContext() throws Exception {
    final HttpGet httpget = new HttpGet("http://somehost/stuff");
    final HttpClientContext context = HttpClientContext.create();

    final Lookup<CookieSpecProvider> localCookieSpecRegistry = Mockito.mock(Lookup.class);
    final Lookup<AuthSchemeProvider> localAuthSchemeRegistry = Mockito.mock(Lookup.class);
    final CookieStore localCookieStore = Mockito.mock(CookieStore.class);
    final CredentialsProvider localCredentialsProvider = Mockito.mock(CredentialsProvider.class);
    final RequestConfig localConfig = RequestConfig.custom().build();

    context.setCookieSpecRegistry(localCookieSpecRegistry);
    context.setAuthSchemeRegistry(localAuthSchemeRegistry);
    context.setCookieStore(localCookieStore);
    context.setCredentialsProvider(localCredentialsProvider);
    context.setRequestConfig(localConfig);

    client.execute(httpget, context);

    Assert.assertSame(localCookieSpecRegistry, context.getCookieSpecRegistry());
    Assert.assertSame(localAuthSchemeRegistry, context.getAuthSchemeRegistry());
    Assert.assertSame(localCookieStore, context.getCookieStore());
    Assert.assertSame(localCredentialsProvider, context.getCredentialsProvider());
    Assert.assertSame(localConfig, context.getRequestConfig());
}
 
开发者ID:MyPureCloud,项目名称:purecloud-iot,代码行数:27,代码来源:TestInternalHttpClient.java

示例14: testSessionTimeout

import org.apache.http.client.CookieStore; //导入依赖的package包/类
@Test(timeout = 130000)
public void testSessionTimeout() throws Exception {
    IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME);
    CookieStore cookieStore = new BasicCookieStore();

    // Write a value into the session on one server
    assertEquals("true", executeRequest("write", serverPort1, cookieStore));

    // Find the session in the map and verify that it has one reference
    String sessionId = findHazelcastSessionId(map);
    assertEquals(1, map.size());

    // We want the session lifecycles between the two servers to be offset somewhat, so wait
    // briefly and then read the session state on the second server
    assertEquals("value", executeRequest("read", serverPort2, cookieStore));

    // At this point the session should have two references, one from each server
    assertEquals(1, map.size());

    // Wait for the session to timeout on the other server, at which point it should be
    // fully removed from the map
    Thread.sleep(TimeUnit.SECONDS.toMillis(90L));
    assertTrue("Session timeout on both nodes should have removed the IMap entries", map.isEmpty());
}
 
开发者ID:hazelcast,项目名称:hazelcast-wm,代码行数:25,代码来源:WebFilterSessionCleanupTest.java

示例15: whenClusterIsDown_enabledDeferredWrite

import org.apache.http.client.CookieStore; //导入依赖的package包/类
@Test
public void whenClusterIsDown_enabledDeferredWrite() throws Exception {
    CookieStore cookieStore = new BasicCookieStore();
    assertEquals("true", executeRequest("write", serverPort1, cookieStore));
    assertEquals("value", executeRequest("read", serverPort1, cookieStore));
    hz.shutdown();

    assertEquals("value", executeRequest("read", serverPort1, cookieStore));
    assertEquals("true", executeRequest("remove", serverPort1, cookieStore));
    assertEquals("null", executeRequest("read", serverPort1, cookieStore));

    hz = Hazelcast.newHazelcastInstance(
            new FileSystemXmlConfig(new File(sourceDir + "/WEB-INF/", "hazelcast.xml")));
    assertClusterSizeEventually(1, hz);

    assertEquals("true", executeRequest("write", serverPort1, cookieStore));
    assertEquals("value", executeRequest("read", serverPort1, cookieStore));
}
 
开发者ID:hazelcast,项目名称:hazelcast-wm,代码行数:19,代码来源:WebFilterClientFailOverTests.java


注:本文中的org.apache.http.client.CookieStore类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。