下面列出了org.apache.http.client.CookieStore#addCookie ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
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;
}
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);
}
}
@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;
}
@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);
}
}
@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);
}
}
/**
* 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;
}
/**
* 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);
}
}
@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));
}
/**
* 获取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();
}
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;
}
/**
* 获取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();
}
/**
* 设置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);
}
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);
}
/**
* 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);
}
}
@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));
}
/**
* 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);
}
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 );
}
/**
* 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);
}
}
/**
* 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"));
}