Java Code Examples for org.apache.http.client.CookieStore#addCookie()
The following examples show how to use
org.apache.http.client.CookieStore#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: HttpUriRequestConverter.java From webmagic with Apache License 2.0 | 6 votes |
private HttpClientContext convertHttpClientContext(Request request, Site site, Proxy proxy) { HttpClientContext httpContext = new HttpClientContext(); if (proxy != null && proxy.getUsername() != null) { AuthState authState = new AuthState(); authState.update(new BasicScheme(ChallengeState.PROXY), new UsernamePasswordCredentials(proxy.getUsername(), proxy.getPassword())); httpContext.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState); } if (request.getCookies() != null && !request.getCookies().isEmpty()) { CookieStore cookieStore = new BasicCookieStore(); for (Map.Entry<String, String> cookieEntry : request.getCookies().entrySet()) { BasicClientCookie cookie1 = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue()); cookie1.setDomain(UrlUtils.removePort(UrlUtils.getDomain(request.getUrl()))); cookieStore.addCookie(cookie1); } httpContext.setCookieStore(cookieStore); } return httpContext; }
Example 2
Source File: CookieHttpClientFactory.java From olingo-odata4 with Apache License 2.0 | 6 votes |
@Override public DefaultHttpClient create(final HttpMethod method, final URI uri) { final CookieStore cookieStore = new BasicCookieStore(); // Populate cookies if needed final BasicClientCookie cookie = new BasicClientCookie("name", "value"); cookie.setVersion(0); cookie.setDomain(".mycompany.com"); cookie.setPath("/"); cookieStore.addCookie(cookie); final DefaultHttpClient httpClient = super.create(method, uri); httpClient.setCookieStore(cookieStore); return httpClient; }
Example 3
Source File: JLineupHttpClient.java From jlineup with Apache License 2.0 | 6 votes |
private void addCookiesToStore(List<Cookie> cookies, CookieStore cookieStore, String domain) { for (Cookie cookie : cookies) { BasicClientCookie apacheCookie = new BasicClientCookie(cookie.name, cookie.value); apacheCookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true"); if (cookie.domain != null) { apacheCookie.setDomain(cookie.domain); } else { apacheCookie.setDomain(domain); } if (cookie.expiry != null) { apacheCookie.setExpiryDate(cookie.expiry); } if (cookie.path != null) { apacheCookie.setPath(cookie.path); } apacheCookie.setSecure(cookie.secure); cookieStore.addCookie(apacheCookie); } }
Example 4
Source File: AsyncHttpClient.java From letv with Apache License 2.0 | 6 votes |
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; }
Example 5
Source File: AzkabanProjectService.java From DataSphereStudio with Apache License 2.0 | 5 votes |
/** * delete=boolean * project=projectName * * @param project * @param session */ @Override public void deleteProject(Project project, Session session) throws AppJointErrorException { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("delete", "true")); params.add(new BasicNameValuePair("project", project.getName())); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(session.getCookies()[0]); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse response = null; CloseableHttpClient httpClient = null; try { String finalUrl = projectUrl + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params)); HttpGet httpGet = new HttpGet(finalUrl); httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8"); httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); response = httpClient.execute(httpGet, context); Header[] allHeaders = context.getRequest().getAllHeaders(); Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getName())).findFirst(); header.ifPresent(DSSExceptionUtils.handling(this::parseCookie)); } catch (Exception e) { logger.error("delete scheduler project failed,reason:",e); throw new AppJointErrorException(90010, e.getMessage(), e); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(httpClient); } }
Example 6
Source File: CookiesPathTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testMultipleCookies() throws IOException { String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account"; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); // create old cookie with wrong path BasicClientCookie wrongCookie = new BasicClientCookie(AuthenticationSessionManager.AUTH_SESSION_ID, AUTH_SESSION_VALUE); wrongCookie.setDomain(AUTH_SERVER_HOST); wrongCookie.setPath(OLD_COOKIE_PATH); wrongCookie.setExpiryDate(calendar.getTime()); // obtain new cookies CookieStore cookieStore = getCorrectCookies(requestURI); cookieStore.addCookie(wrongCookie); Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3)); login(requestURI, cookieStore); // old cookie has been removed // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), Matchers.hasItems("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION")); // does each cookie's path end with "/" cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())).map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/"))); // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue(); String KCSessionId = cookieStore.getCookies().stream().filter(c -> "KEYCLOAK_SESSION".equals(c.getName())).findFirst().get().getValue(); String KCSessionSuffix = KCSessionId.split("/")[2]; Assert.assertThat(authSessionId, Matchers.containsString(KCSessionSuffix)); }
Example 7
Source File: AzkabanProjectService.java From DataSphereStudio with Apache License 2.0 | 5 votes |
/** * parameters: * name = value * description=value * * @param project * @param session * @throws AppJointErrorException */ @Override public Project createProject(Project project, Session session) throws AppJointErrorException { List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("action", "create")); params.add(new BasicNameValuePair("name", project.getName())); params.add(new BasicNameValuePair("description", project.getDescription())); HttpPost httpPost = new HttpPost(projectUrl); httpPost.addHeader(HTTP.CONTENT_ENCODING, HTTP.IDENTITY_CODING); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(session.getCookies()[0]); HttpEntity entity = EntityBuilder.create() .setContentType(ContentType.create("application/x-www-form-urlencoded", Consts.UTF_8)) .setParameters(params).build(); httpPost.setEntity(entity); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); response = httpClient.execute(httpPost); HttpEntity ent = response.getEntity(); String entStr = IOUtils.toString(ent.getContent(), "utf-8"); logger.error("新建工程 {}, azkaban 返回的信息是 {}", project.getName(), entStr); String message = AzkabanUtils.handleAzkabanEntity(entStr); if (!"success".equals(message)) { throw new AppJointErrorException(90008, "新建工程失败, 原因:" + message); } } catch (Exception e) { logger.error("创建工程失败:", e); throw new AppJointErrorException(90009, e.getMessage(), e); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(httpClient); } return null; }
Example 8
Source File: HttpManager.java From NetDiscovery with Apache License 2.0 | 5 votes |
/** * 获取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) // 302跳转 .setRedirectStrategy(new RedirectStrategy()); if (cookie!=null) { CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); httpClientBuilder.setDefaultCookieStore(cookieStore); } return httpClientBuilder.build(); }
Example 9
Source File: Http4FileProvider.java From commons-vfs with Apache License 2.0 | 5 votes |
private CookieStore createDefaultCookieStore(final Http4FileSystemConfigBuilder builder, final FileSystemOptions fileSystemOptions) { final CookieStore cookieStore = new BasicCookieStore(); final Cookie[] cookies = builder.getCookies(fileSystemOptions); if (cookies != null) { for (final Cookie cookie : cookies) { cookieStore.addCookie(cookie); } } return cookieStore; }
Example 10
Source File: HttpManager.java From ProxyPool with Apache License 2.0 | 5 votes |
/** * 获取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(); }
Example 11
Source File: HttpTest.java From DataSphereStudio with Apache License 2.0 | 5 votes |
@Test public void test03() throws IOException, SchedulisSchedulerException { Cookie cookie = test01(); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("ajax","fetchProjectPage")); params.add(new BasicNameValuePair("start","0")); params.add(new BasicNameValuePair("length","10")); params.add(new BasicNameValuePair("projectsType","personal")); params.add(new BasicNameValuePair("pageNum","1")); params.add(new BasicNameValuePair("order","orderProjectName")); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse response = null; CloseableHttpClient httpClient = null; try { String finalUrl = "http://127.0.0.1:8088/index" + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params)); HttpGet httpGet = new HttpGet(finalUrl); httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8"); httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); response = httpClient.execute(httpGet, context); /*Header[] allHeaders = context.getRequest().getAllHeaders(); Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getAppJointName())).findFirst(); header.ifPresent(AzkabanUtils.handlingConsumerWrapper(this::parseCookie));*/ } catch (Exception e) { throw new SchedulisSchedulerException(90002, e.getMessage()); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(httpClient); } }
Example 12
Source File: AsyncNetwork.java From jlitespider with Apache License 2.0 | 5 votes |
/** * 设置cookie * @param cookies */ public void setCookie(Map<String, String> cookies) { CookieStore cookieStore = new BasicCookieStore(); for (Map.Entry<String, String> each : cookies.entrySet()) { cookieStore.addCookie(new BasicClientCookie(each.getKey(), each.getValue())); } httpAsyncClientBuilder.setDefaultCookieStore(cookieStore); }
Example 13
Source File: ClanUtils.java From BigApp_Discuz_Android with Apache License 2.0 | 5 votes |
public static void pushCookie(Context context, String cookieStr) { if (StringUtils.isEmptyOrNullOrNullStr(cookieStr)) return; com.youzu.clan.base.net.CookieManager cm = com.youzu.clan.base.net.CookieManager.getInstance(); // PersistentCookieStore cookieStore = new PersistentCookieStore(context); CookieStore cookieStore = cm.getCookieStore(context); // ClanBaseUtils.printCookieStore(cookieStore); String[] kvs = cookieStr.split("; "); for (String s : kvs) { String[] kv = s.split("="); String key = ""; String value = ""; if (kv.length >= 1) { key = kv[0]; } if (kv.length >= 1) { value = kv[1]; } Log.e("APP", "key:" + key + " value:" + value); MyCooike cookie = new MyCooike(key, value); // cm.getCookieStore(context).addCookie(cookie); cookie.setDomain(ClanUtils.getDomainName(Url.DOMAIN)); cookie.setPath("/"); cookieStore.addCookie(cookie); } HttpUtils httpUtils = new HttpUtils(60 * 1000); httpUtils.configCookieStore(cookieStore); }
Example 14
Source File: ApacheCloudStackClient.java From apache-cloudstack-java-client with Apache License 2.0 | 5 votes |
/** * This method creates a cookie for every {@link HeaderElement} of the {@link Header} given as parameter. * Then, it adds this newly created cookie into the {@link CookieStore} provided as parameter. */ protected void createAndAddCookiesOnStoreForHeader(CookieStore cookieStore, Header header) { for (HeaderElement element : header.getElements()) { BasicClientCookie cookie = createCookieForHeaderElement(element); cookieStore.addCookie(cookie); } }
Example 15
Source File: CookiesPathTest.java From keycloak with Apache License 2.0 | 5 votes |
@Test public void testOldCookieWithNodeInValue() throws IOException { String requestURI = OAuthClient.AUTH_SERVER_ROOT + "/realms/foo/account"; Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DAY_OF_YEAR, 1); // create old cookie with wrong path BasicClientCookie wrongCookie = new BasicClientCookie(AuthenticationSessionManager.AUTH_SESSION_ID, AUTH_SESSION_VALUE_NODE); wrongCookie.setDomain(AUTH_SERVER_HOST); wrongCookie.setPath(OLD_COOKIE_PATH); wrongCookie.setExpiryDate(calendar.getTime()); // obtain new cookies CookieStore cookieStore = getCorrectCookies(requestURI); cookieStore.addCookie(wrongCookie); Assert.assertThat(cookieStore.getCookies(), Matchers.hasSize(3)); login(requestURI, cookieStore); // old cookie has been removed // now we have AUTH_SESSION_ID, KEYCLOAK_IDENTITY, KEYCLOAK_SESSION, OAuth_Token_Request_State Assert.assertThat(cookieStore.getCookies().stream().map(org.apache.http.cookie.Cookie::getName).collect(Collectors.toList()), Matchers.hasItems("AUTH_SESSION_ID", "KEYCLOAK_IDENTITY", "KEYCLOAK_SESSION")); // does each cookie's path end with "/" cookieStore.getCookies().stream().filter(c -> !"OAuth_Token_Request_State".equals(c.getName())).map(org.apache.http.cookie.Cookie::getPath).forEach(path ->Assert.assertThat(path, Matchers.endsWith("/"))); // KEYCLOAK_SESSION should end by AUTH_SESSION_ID value String authSessionId = cookieStore.getCookies().stream().filter(c -> "AUTH_SESSION_ID".equals(c.getName())).findFirst().get().getValue(); String KCSessionId = cookieStore.getCookies().stream().filter(c -> "KEYCLOAK_SESSION".equals(c.getName())).findFirst().get().getValue(); String KCSessionSuffix = KCSessionId.split("/")[2]; Assert.assertThat(authSessionId, Matchers.containsString(KCSessionSuffix)); }
Example 16
Source File: NUHttpClient.java From neembuu-uploader with GNU General Public License v3.0 | 5 votes |
/** * 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 17
Source File: cfHttpConnection.java From openbd-core with GNU General Public License v3.0 | 5 votes |
private void addCookies() { Map<String, List<String>> cookies = httpData.getCookies(); Iterator<String> keys = cookies.keySet().iterator(); String domain = ""; domain = message.getURI().getHost(); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute( ClientContext.COOKIE_STORE, cookieStore ); client.getParams().setParameter( ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY ); while ( keys.hasNext() ) { String nextKey = keys.next(); List<String> values = cookies.get( nextKey ); Date date = new Date( 2038, 1, 1 ); for ( int i = 0; i < values.size(); i++ ) { BasicClientCookie cookie = new BasicClientCookie( nextKey, values.get( i ) ); cookieStore.addCookie( cookie ); cookie.setVersion( 1 ); cookie.setDomain( domain ); cookie.setPath( "/" ); cookie.setExpiryDate( date ); cookie.setSecure( false ); } } client.setCookieStore( cookieStore ); }
Example 18
Source File: HttpTest.java From DataSphereStudio with Apache License 2.0 | 5 votes |
@Test public void test03() throws IOException, SchedulisSchedulerException { Cookie cookie = test01(); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("ajax","fetchProjectPage")); params.add(new BasicNameValuePair("start","0")); params.add(new BasicNameValuePair("length","10")); params.add(new BasicNameValuePair("projectsType","personal")); params.add(new BasicNameValuePair("pageNum","1")); params.add(new BasicNameValuePair("order","orderProjectName")); CookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(cookie); HttpClientContext context = HttpClientContext.create(); CloseableHttpResponse response = null; CloseableHttpClient httpClient = null; try { String finalUrl = "http://127.0.0.1:8088/index" + "?" + EntityUtils.toString(new UrlEncodedFormEntity(params)); HttpGet httpGet = new HttpGet(finalUrl); httpGet.addHeader(HTTP.CONTENT_ENCODING, "UTF-8"); httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); response = httpClient.execute(httpGet, context); /*Header[] allHeaders = context.getRequest().getAllHeaders(); Optional<Header> header = Arrays.stream(allHeaders).filter(f -> "Cookie".equals(f.getAppJointName())).findFirst(); header.ifPresent(AzkabanUtils.handlingConsumerWrapper(this::parseCookie));*/ } catch (Exception e) { throw new SchedulisSchedulerException(90004, e.getMessage()); } finally { IOUtils.closeQuietly(response); IOUtils.closeQuietly(httpClient); } }
Example 19
Source File: CookieConverter.java From hsac-fitnesse-fixtures with Apache License 2.0 | 5 votes |
/** * Converts Selenium cookies to Apache http client ones. * @param browserCookies cookies in Selenium format. * @param cookieStore store to place coverted cookies in. */ public void copySeleniumCookies(Set<Cookie> browserCookies, CookieStore cookieStore) { for (Cookie browserCookie : browserCookies) { ClientCookie cookie = convertCookie(browserCookie); cookieStore.addCookie(cookie); } }
Example 20
Source File: VaryMasterTest.java From esigate with Apache License 2.0 | 5 votes |
/** * Send a request with a Cookie "test-cookie" to vary.jsp (which will get content from provider) and ensure the * result is valid. * * @param cookieValue * @param forceRefresh * @return Page timestamp. Can be used to detect cache hits. * @throws Exception */ private String doCookieRequest(String cookieValue, boolean forceRefresh) throws Exception { CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = new HttpClientContext(); context.setCookieStore(cookieStore); CloseableHttpClient client = HttpClients.createDefault(); RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); HttpGet request = new HttpGet("http://localhost:8080/esigate-app-master/vary.jsp"); request.setConfig(config); if (cookieValue != null) { BasicClientCookie cookie = new BasicClientCookie("test-cookie", cookieValue); cookie.setDomain("localhost"); cookie.setPath("/"); cookieStore.addCookie(cookie); } if (forceRefresh) { request.addHeader("Cache-Control", "no-cache"); } HttpResponse response = client.execute(request, context); // Ensure content is valid. String text = IOUtils.toString(response.getEntity().getContent()); assertNotNull(text); LOG.debug("----- Request with cookie " + cookieValue + " and forceRefresh=" + forceRefresh + " -----> \n" + text); if (cookieValue != null) { assertTrue("no value '" + cookieValue + "' found", text.contains(cookieValue)); } else { assertTrue("no cookie found", text.contains("no cookie")); } client.close(); return text.substring(text.indexOf("stime") + 5, text.indexOf("etime")); }