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(); } } }
/** * 将登录结果保存到给定会话对象中,并激活给定会话对象。 * @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); } }
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; }
protected HttpContext createHttpContext(HttpProxy httpProxy, CookieStore cookieStore) { HttpContext httpContext = new HttpClientContext(); if (cookieStore != null) { httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); } if (httpProxy != null && StringUtils.isNotBlank(httpProxy.getUsername())) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(httpProxy.getHost(), httpProxy.getPort()), new UsernamePasswordCredentials(httpProxy.getUsername(), httpProxy.getPassword())); httpContext.setAttribute(HttpClientContext.CREDS_PROVIDER, credentialsProvider); } return httpContext; }
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; }
/** * 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("/$", ""); }
/** * 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); }
/** 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()]); }
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(); }
@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; } }
@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); }
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; }
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()); }
@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()); }
@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()); }
@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)); }
@Test(timeout = 80000) public void testAttributeInvalidate() throws Exception { CookieStore cookieStore = new BasicCookieStore(); executeRequest("write", SERVER_PORT_1, cookieStore); String value = executeRequest("read", SERVER_PORT_1, cookieStore); assertEquals("value", value); value = executeRequest("invalidate", SERVER_PORT_1, cookieStore); assertEquals("true", value); HazelcastInstance instance = createHazelcastInstance(); IMap<Object, Object> map = instance.getMap("default"); assertEquals(0, map.size()); }
@Test public void testWhenClusterIsDownAtBeginningInNonDeferredMode() throws Exception { if (!testName.equals("client - not deferred")) { return; } hz.shutdown(); CookieStore cookieStore = new BasicCookieStore(); assertEquals("true", executeRequest("write", serverPort1, cookieStore)); assertEquals("value", executeRequest("read", serverPort1, cookieStore)); hz = Hazelcast.newHazelcastInstance( new FileSystemXmlConfig(new File(sourceDir + "/WEB-INF/", "hazelcast.xml"))); assertClusterSizeEventually(1, hz); assertEquals("value", executeRequest("read", serverPort1, cookieStore)); IMap<String, Object> map = hz.getMap(DEFAULT_MAP_NAME); assertEquals(1, map.size()); }
public String readCookieStoreValue(final String name) { if (StringUtils.isBlank(name)) { throw new CloudDiskException("cookie名称不能为空"); } final CookieStore cookieStore = httpClientContext.getCookieStore(); final List<Cookie> cookies = cookieStore.getCookies(); Cookie cookie = null; for (final Cookie coo : cookies) { if (coo.getName().equals(name)) { cookie = coo; break; } } if (null != cookie) { return cookie.getValue(); } return null; }
@Test(timeout = 60000) public void test_multipleRequest() throws Exception { final CookieStore cookieStore = new BasicCookieStore(); executeRequest("read", serverPort1, cookieStore); Thread thread = new Thread(new Runnable() { @Override public void run() { try { executeRequest("write_wait", serverPort1, cookieStore); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); Thread.sleep(500); executeRequest("read", serverPort1, cookieStore); thread.join(); assertEquals("value", executeRequest("read", serverPort1, cookieStore)); }
@Override public BasicHttpContext createContext(final HttpHost targetHost) { BasicHttpContext context = CACHED_CONTEXTS.get(targetHost); if (context == null) { log.trace("creating and configuring new HttpContext for system user"); context = basicAuthConfigurator.createContext(targetHost); final CookieStore cookieStore = new BasicCookieStore(); context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); log.trace("caching HttpContext for system user"); CACHED_CONTEXTS.put(targetHost, context); } else { log.trace("using cached HttpContext for system user"); } return context; }
private HttpClientContext createContext(Authentication auth, HttpHost target) { HttpClientContext httpClientContext = HttpClientContext.create(); CookieStore cookieStore = new BasicCookieStore(); httpClientContext.setCookieStore(cookieStore); if (auth.usePreemptiveAuthentication()) { httpClientContext.setAuthCache(new Auth().getAuthCache(auth, target)); } return httpClientContext; }
@Override public void addAuth(HttpRequestBase request, CookieStore cookieStore) { String basicAuthUnencoded = String.format("%s:%s", username, password); String basicAuth = "Basic " + BaseEncoding.base64().encode(basicAuthUnencoded.getBytes()); request.addHeader("Authorization", basicAuth); }
protected SlingClientConfig(URI url, String user, String password, CookieStore cookieStore, CredentialsProvider credentialsProvider, AuthCache authCache) { this.url = url; this.user = user; this.password = password; this.cookieStore = cookieStore; this.credsProvider = credentialsProvider; this.authCache = authCache; this.values = new ConcurrentHashMap<String, String>(); }
/** * Extract the sessionId from the response cookies * * @param context the context holding the cookies * * @return the sessionId if found * * @throws IOException */ private Optional<String> extractSessionId(HttpClientContext context) { CookieStore cookieStore = context.getCookieStore(); Set<String> jSessionCookies = cookieStore.getCookies().stream() .filter(c -> c.getName().equals("JSESSIONID")) .map(Cookie::getValue).collect(Collectors.toSet()); Iterator<String> it = jSessionCookies.iterator(); if (!it.hasNext()) { return Optional.empty(); } else { return Optional.of(it.next()); } }
/** * 获取Http客户端连接对象 * @param timeOut 超时时间 * @param proxy 代理 * @param cookie Cookie * @return Http客户端连接对象 */ public CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) { // 创建Http请求配置参数 RequestConfig.Builder builder = RequestConfig.custom() // 获取连接超时时间 .setConnectionRequestTimeout(timeOut) // 请求超时时间 .setConnectTimeout(timeOut) // 响应超时时间 .setSocketTimeout(timeOut) .setCookieSpec(CookieSpecs.STANDARD); if (proxy!=null) { builder.setProxy(proxy); } RequestConfig requestConfig = builder.build(); // 创建httpClient HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder // 把请求相关的超时信息设置到连接客户端 .setDefaultRequestConfig(requestConfig) // 把请求重试设置到连接客户端 .setRetryHandler(new RetryHandler()) // 配置连接池管理对象 .setConnectionManager(connManager); if (cookie!=null) { CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); httpClientBuilder.setDefaultCookieStore(cookieStore); } return httpClientBuilder.build(); }
/** * 获取Http客户端连接对象 * @param timeOut 超时时间 * @param proxy 代理 * @param cookie Cookie * @return Http客户端连接对象 */ private CloseableHttpClient createHttpClient(int timeOut,HttpHost proxy,BasicClientCookie cookie) { // 创建Http请求配置参数 RequestConfig.Builder builder = RequestConfig.custom() // 获取连接超时时间 .setConnectionRequestTimeout(timeOut) // 请求超时时间 .setConnectTimeout(timeOut) // 响应超时时间 .setSocketTimeout(timeOut) .setCookieSpec(CookieSpecs.STANDARD); if (proxy!=null) { builder.setProxy(proxy); } RequestConfig requestConfig = builder.build(); // 创建httpClient HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder // 把请求相关的超时信息设置到连接客户端 .setDefaultRequestConfig(requestConfig) // 把请求重试设置到连接客户端 .setRetryHandler(new RetryHandler()) // 配置连接池管理对象 .setConnectionManager(connManager); if (cookie!=null) { CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); httpClientBuilder.setDefaultCookieStore(cookieStore); } return httpClientBuilder.build(); }
public static CloseableHttpClient get(String trustStoreFile, String trustStoreType, String trustStorePass, String keyStoreFile, String keyStoreType, String keyStorePass, CookieStore cookieStore, boolean hostVerificationEnabled) { SSLContext ssl = getSSLContext(trustStoreFile, trustStoreType, trustStorePass, keyStoreFile, keyStoreType, keyStorePass); return get(ssl, cookieStore, hostVerificationEnabled); }
public static CloseableHttpClient get(SSLContext ssl, CookieStore cookieStore, boolean hostVerificationEnabled) { RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); HttpClientBuilder builder = HttpClients.custom().setSSLContext(ssl).setDefaultCookieStore(cookieStore) .setDefaultRequestConfig(defaultRequestConfig); if (hostVerificationEnabled) { builder.setSSLHostnameVerifier(new DefaultHostnameVerifier()); } else { builder.setSSLHostnameVerifier(new NoopHostnameVerifier()); } return builder.build(); }
/** * @param username Username * @param password Password * @param uuid UUID * @param cookieStore Cookie Store */ @Builder public Instagram4j(String username, String password, String uuid, CookieStore cookieStore) { super(); this.username = username; this.password = password; this.uuid = uuid; this.cookieStore = cookieStore; this.isLoggedIn = true; }
/** * Initializes an http communication session with the application. */ public ApplicationSession authenticate(Application application) { String uri = application.makeHostnameUri() + "/" + DbFreezeRest.POST_LOGIN; Executor httpExecutor = executorFactory.makeExecutor(); CookieStore cookieStore = new BasicCookieStore(); httpExecutor.cookieStore(cookieStore); NameValuePair[] authParams = new NameValuePair[] { new BasicNameValuePair(PARAMNAME_AUTHUSERNAME, applicationUsername), new BasicNameValuePair(PARAMNAME_AUTHPASSWORD, applicationPassword) }; httpHelper.postAuthForCookie(httpExecutor, uri, authParams); return new ApplicationSession(httpExecutor, cookieStore); }
/** * Check if PHPSESSID cookie is set. * * @param cookieStore * @return true if session cookie is set. */ public static boolean hasSessionCookie(CookieStore cookieStore) { for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equalsIgnoreCase("PHPSESSID")) { return true; } } return false; }
@Bean public RestTemplate restTemplate() { CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); httpContext.setAttribute(HttpClientContext.REQUEST_CONFIG, RequestConfig.custom().setRedirectsEnabled(false).build()); return new StatefullRestTemplate(httpContext); }
private void appendAdditionalCookies(CookieStore store, Map<String, String> cookies, String domain, String path, Date expiryDate) { cookies.forEach((key, value) -> { BasicClientCookie cookie = new BasicClientCookie(key, value); cookie.setDomain(domain); cookie.setPath(path); cookie.setExpiryDate(expiryDate); store.addCookie(cookie); }); }
/** * 根据配置自动生成需要的Cookies * @param httpClient * @param setting */ public void generateCookies(HttpClientBuilder httpClient, Setting setting){ CookieStore cookieStore = new BasicCookieStore(); for(Map.Entry<String,String> cookieEntry : setting.getCookies().entrySet()){ BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue()); cookie.setDomain(setting.getDomain()); cookie.setPath("/"); cookieStore.addCookie(cookie); httpClient.setDefaultCookieStore(cookieStore).build(); } }
/** * Get a cookie from Google and place it in a ClosableHttpClient * @return An instance of CloseableHttpClient that is critical to this Class * @throws IOException When URL connection is improperly formed */ private static CloseableHttpClient getCookieHttpClient() throws IOException { /* * Tutorial: http://www.hccp.org/java-net-cookie-how-to.html */ URL myUrl = new URL("https://trends.google.com"); URLConnection urlConn = myUrl.openConnection(); urlConn.connect(); String headerName = null; for(int i=1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) if(headerName.equals("Set-Cookie")) cookieString = urlConn.getHeaderField(i); cookieString = cookieString.substring(0, cookieString.indexOf(";")); /* * Tutorial: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/statemgmt.html#d5e499 */ CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("Cookie", cookieString); cookie.setDomain(".google.com"); cookie.setPath("/trends"); cookieStore.addCookie(cookie); return HttpClients.custom().setDefaultCookieStore(cookieStore).build(); }
public static CloseableHttpClient getHttpClient(final HttpHost proxy, final boolean redirects, final CookieStore cookieStore) { final Builder builder = RequestConfig.custom() .setRedirectsEnabled(redirects) .setMaxRedirects(5); if (proxy != null) builder.setProxy(proxy); final RequestConfig requestConfig = builder.build(); return HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore) .setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE) .build(); }
@Test public void testNoCookies() throws Exception { HttpGet httpget = new HttpGet("http://localhost:8192/"); ResponseHandler<String> responseHandler = new BasicResponseHandler(); this.httpclient.execute(httpget, responseHandler); CookieStore cookies = this.httpclient.getCookieStore(); assertEquals(0, cookies.getCookies().size()); }
@Test(timeout = 80000) public void test_isNew() throws Exception { CookieStore cookieStore = new BasicCookieStore(); assertEquals("true", executeRequest("isNew", SERVER_PORT_1, cookieStore)); assertEquals("false", executeRequest("isNew", SERVER_PORT_1, cookieStore)); }