下面列出了org.apache.http.client.CookieStore#getCookies ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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))
);
}
/** 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()]);
}
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;
}
@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"));
}
/**
* 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;
}
/**
* 获取新浪单点登录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;
}
/**
* 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()});
}
}
/**
* @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;
}
private String getCredentialCookie(CookieStore cookieStore) {
for (Cookie cookie : cookieStore.getCookies()) {
if ("laitnederc-sukrauq".equals(cookie.getName())) {
return cookie.getValue();
}
}
return null;
}
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();
}
}
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;
}
/**
* 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;
}
/**
* 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;
}
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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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);
}
/**
* 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;
}
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();
}
}
}
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;
}