下面列出了怎么用org.apache.http.cookie.Cookie的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
void shouldSetCookiesFromBrowserAndDelegateRequestToApiSteps()
{
CookieStore cookieStore = mock(CookieStore.class);
when(cookieManager.getCookiesAsHttpCookieStore()).thenReturn(cookieStore);
BasicClientCookie cookie1 = new BasicClientCookie("key", "vale");
BasicClientCookie cookie2 = new BasicClientCookie("key1", "vale1");
when(cookieStore.getCookies()).thenReturn(List.of(cookie1, cookie2));
httpRequestSteps.executeRequestUsingBrowserCookies();
verify(httpTestContext).putCookieStore(cookieStore);
verify(attachmentPublisher).publishAttachment(eq("org/vividus/bdd/steps/integration/browser-cookies.ftl"),
argThat(arg ->
{
@SuppressWarnings("unchecked")
List<Cookie> cookies = ((Map<String, List<Cookie>>) arg).get("cookies");
return cookies.size() == 2
&& cookies.get(0).toString().equals(
"[version: 0][name: key][value: vale][domain: null][path: null][expiry: null]")
&& cookies.get(1).toString().equals(
"[version: 0][name: key1][value: vale1][domain: null][path: null][expiry: null]");
}), eq("Browser cookies"));
}
@Override
public void addCookie(Cookie cookie) {
String name = cookie.getName() + cookie.getDomain();
// Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
prefsWriter.commit();
}
@Override
public void addCookie(Cookie cookie) {
String name = cookie.getName();
// Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
Set<String> keySet = cookies.keySet();
userPreferences.setProperty(COOKIE_NAME_STORE,
join(",", keySet));
userPreferences.setProperty(COOKIE_NAME_PREFIX + name,
encodeCookie(new SerializableCookie(cookie)));
UserPreference.getInstance().saveUserPreferences();
}
/**
* Get a string with all the cookies.
* @param httpContext the context.
* @param separator the separator string between cookies.
* @return a new string with all the cookies.
*/
public static String getAllCookies(HttpContext httpContext, String separator){
CookieStore cookieStore = (CookieStore) httpContext.getAttribute(ClientContext.COOKIE_STORE);
List<Cookie> cookies = cookieStore.getCookies();
String cookieName;
String cookieValue;
StringBuilder result = new StringBuilder();
for(int i = 0; i < cookies.size(); i++){
cookieName = cookies.get(i).getName();
cookieValue = cookies.get(i).getValue();
result
.append(cookieName)
.append("=")
.append(cookieValue)
.append(separator);
}
return result.toString();
}
@Override
public void addCookie(Cookie cookie) {
if (omitNonPersistentCookies && !cookie.isPersistent())
return;
String name = cookie.getName() + cookie.getDomain();
// Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
prefsWriter.commit();
}
@Override
public void addCookie(Cookie cookie) {
if (omitNonPersistentCookies && !cookie.isPersistent())
return;
String name = cookie.getName() + cookie.getDomain();
// Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
prefsWriter.commit();
}
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new ConcurrentHashMap<String, Cookie>();
// Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
}
// Clear out expired cookies
clearExpired(new Date());
}
}
@Test
public void testNotExpiredCookie() {
String[] cookiesStrings = new String[1];
String dummyCookieString = buildCookieString(dummyCookieHeader,
dummyCookieValue, null, "Tue, 11 Apr 2117 07:13:39 -0000",
null, null);
cookiesStrings[0] = dummyCookieString;
List<Cookie> result = CookieConverter.getCookies(cookiesStrings,
getUrl(unsecuredUrl));
Assert.assertEquals("Should have 1 cookie", 1, result.size());
Assert.assertEquals("Cookie header should be as defined",
dummyCookieHeader, result.get(0).getName());
Assert.assertEquals("Cookie value should be as defined",
dummyCookieValue, result.get(0).getValue());
}
/**
* Construct a persistent cookie store.
*/
public PreferencesCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, Context.MODE_PRIVATE);
cookies = new ConcurrentHashMap<String, Cookie>();
// Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
}
// Clear out expired cookies
clearExpired(new Date());
}
}
public Cookie test01() throws IOException {
HttpPost httpPost = new HttpPost("http://127.0.0.1:8088/checkin");
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("username", "neiljianliu"));
params.add(new BasicNameValuePair("userpwd", "*****"));
params.add(new BasicNameValuePair("action", "login"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
CookieStore cookieStore = new BasicCookieStore();
CloseableHttpClient httpClient = null;
CloseableHttpResponse response = null;
HttpClientContext context = null;
try {
httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
context = HttpClientContext.create();
response = httpClient.execute(httpPost, context);
} finally {
IOUtils.closeQuietly(response);
IOUtils.closeQuietly(httpClient);
}
List<Cookie> cookies = context.getCookieStore().getCookies();
return cookies.get(0);
}
/**
* Construct a persistent cookie store.
*
* @param context Context to attach cookie store to
*/
public PersistentCookieStore(Context context) {
cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
cookies = new ConcurrentHashMap<String, Cookie>();
// Load any previously stored cookies into the store
String storedCookieNames = cookiePrefs.getString(COOKIE_NAME_STORE, null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
}
// Clear out expired cookies
clearExpired(new Date());
}
}
@Override
public void addCookie(Cookie cookie) {
if (omitNonPersistentCookies && !cookie.isPersistent())
return;
String name = cookie.getName() + cookie.getDomain();
// Save cookie into local store, or remove if expired
if (!cookie.isExpired(new Date())) {
cookies.put(name, cookie);
} else {
cookies.remove(name);
}
// Save cookie into persistent store
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
prefsWriter.putString(COOKIE_NAME_PREFIX + name, encodeCookie(new SerializableCookie(cookie)));
prefsWriter.commit();
}
/**
* Look for session cookies.
*
* @return true if session cookies are available
*/
protected boolean isAuthenticated(ResponseWrapper getRequest) {
boolean authenticated = false;
if (getRequest.getStatusCode() == HttpStatus.SC_OK
&& "/ews/services.wsdl".equalsIgnoreCase(getRequest.getURI().getPath())) {
// direct EWS access returned wsdl
authenticated = true;
} else {
// check cookies
for (Cookie cookie : httpClientAdapter.getCookies()) {
// Exchange 2003 cookies
if (cookie.getName().startsWith("cadata") || "sessionid".equals(cookie.getName())
// Exchange 2007 cookie
|| "UserContext".equals(cookie.getName())
) {
authenticated = true;
break;
}
}
}
return authenticated;
}
/**
* Remove a Cookie by name and path
*
* @param name cookie name
* @param path cookie path
*/
@PublicAtsApi
public void removeCookie( String name, String path ) {
BasicCookieStore cookieStore = (BasicCookieStore) httpContext.getAttribute(HttpClientContext.COOKIE_STORE);
if (cookieStore != null) {
List<Cookie> cookies = cookieStore.getCookies();
cookieStore.clear();
for (Cookie cookie : cookies) {
if (!cookie.getName().equals(name) || !cookie.getPath().equals(path)) {
cookieStore.addCookie(cookie);
}
}
}
}
public PersistentCookieStore(Context context) {
int i = 0;
this.cookiePrefs = context.getSharedPreferences(COOKIE_PREFS, 0);
String storedCookieNames = this.cookiePrefs.getString(COOKIE_NAME_STORE, null);
if (storedCookieNames != null) {
String[] cookieNames = TextUtils.split(storedCookieNames, ",");
int length = cookieNames.length;
while (i < length) {
String name = cookieNames[i];
String encodedCookie = this.cookiePrefs.getString(new StringBuilder(COOKIE_NAME_PREFIX).append(name).toString(), null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
this.cookies.put(name, decodedCookie);
}
}
i++;
}
clearExpired(new Date());
}
}
public void reload() {
//todo dir
// Load any previously stored cookies into the store
cookies = new ConcurrentHashMap<String, Cookie>();
String storedCookieNames = userPreferences.getProperty(
COOKIE_NAME_STORE, null);
if (storedCookieNames != null) {
String[] cookieNames = split(storedCookieNames, ",");
for (String name : cookieNames) {
String encodedCookie = userPreferences.getProperty(
COOKIE_NAME_PREFIX + name, null);
if (encodedCookie != null) {
Cookie decodedCookie = decodeCookie(encodedCookie);
if (decodedCookie != null) {
cookies.put(name, decodedCookie);
}
}
}
// Clear out expired cookies
clearExpired(new Date());
}
}
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();
System.out.println(this.statuCode);
try {
this.response = EntityUtils.toByteArray(httpResponse.getEntity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void setCookieFromCookieStore(Context context, String url, List<Cookie> cks) {
CookieUtils.syncCookie(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (!ListUtils.isNullOrContainEmpty(cks)) {
for (int i = 0; i < cks.size(); i++) {
Cookie cookie = cks.get(i);
String cookieStr = cookie.getName() + "=" + cookie.getValue() + ";"
+ "expiry=" + cookie.getExpiryDate() + ";"
+ "domain=" + cookie.getDomain() + ";"
+ "path=/";
// ZogUtils.printError(WebFragment.class, "set cookie string:" + cookieStr);
cookieManager.setCookie(url, cookieStr);//cookieStr是在HttpClient中获得的cookie
}
}
}
public void saveCookie(Cookie cookie) {
L.d("saveCookie:" + cookie);
if (cookie == null) {
return;
}
db.delete(TABLE_NAME, Column.NAME + " = ? ",
new String[] { cookie.getName() });
ContentValues values = new ContentValues();
values.put(Column.VALUE, cookie.getValue());
values.put(Column.NAME, cookie.getName());
values.put(Column.COMMENT, cookie.getComment());
values.put(Column.DOMAIN, cookie.getDomain());
if (cookie.getExpiryDate() != null) {
values.put(Column.EXPIRY_DATE, cookie.getExpiryDate().getTime());
}
values.put(Column.PATH, cookie.getPath());
values.put(Column.SECURE, cookie.isSecure() ? 1 : 0);
values.put(Column.VERSION, cookie.getVersion());
db.insert(TABLE_NAME, null, values);
}
protected Cookie decodeCookie(String cookieStr) {
byte[] bytes = hexStringToByteArray(cookieStr);
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
Cookie cookie = null;
try {
ObjectInputStream ois = new ObjectInputStream(is);
cookie = ((SerializableCookie) ois.readObject()).getCookie();
} catch (Throwable e) {
LogUtils.e(e.getMessage(), e);
}
return cookie;
}
@Test
void testIntegrationMethodsFromCollector()
{
Cookie cookie1 = new BasicClientCookie("name", "value");
Cookie cookie2 = new BasicClientCookie("name2", "value2");
CookieStore cookieStore = Stream.of(cookie1, cookie2).parallel().collect(ClientBuilderUtils.toCookieStore());
assertEquals(cookieStore.getCookies(), List.of(cookie1, cookie2));
}
@Test
public void testInvalidPath() {
String[] cookiesStrings = new String[1];
String dummyCookieString = buildCookieString(dummyCookieHeader,
dummyCookieValue, null, null, "/someFolder", null);
cookiesStrings[0] = dummyCookieString;
List<Cookie> result = CookieConverter.getCookies(cookiesStrings,
getUrl(unsecuredUrl + "/someOtherFolder/SomeFolder"));
Assert.assertEquals("path mismatch, should have 0 cookies", 0,
result.size());
}
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;
}
/**
* @return our session cookie; {@code null} if it doesn't exist
*/
@Nullable
protected Cookie getSessionCookie(final CookieStore cookieStore) {
for (Cookie cookie : cookieStore.getCookies()) {
if (DEFAULT_SESSION_COOKIE_NAME.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
public static Cookie getSessionCookie() {
if (cookieStore == null) {
return null;
}
List<Cookie> cookies = cookieStore.getCookies();
for (Cookie cookie: cookies) {
if (cookie.getDomain().equals(Constants.SESSION_COOKIE_DOMAIN) && cookie.getName().equals("session")) {
return cookie;
}
}
return null;
}
/**
* 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;
}
/**
* @param cookieName name of cookie.
* @param attributeName name of attribute.
* @return value of attribute for cookie.
*/
public String cookieAttribute(String cookieName, String attributeName) {
String result = null;
Cookie cookie = getCookie(cookieName);
if (cookie instanceof BasicClientCookie) {
result = ((BasicClientCookie) cookie).getAttribute(attributeName.toLowerCase(Locale.ENGLISH));
}
return result;
}
/**
* Non-standard helper method, to delete cookie
*
* @param cookie cookie to be removed
*/
public void deleteCookie(Cookie cookie) {
String name = cookie.getName() + cookie.getDomain();
cookies.remove(name);
SharedPreferences.Editor prefsWriter = cookiePrefs.edit();
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
prefsWriter.commit();
}
@Test
public void testValidDomain() {
String[] cookiesStrings = new String[1];
String dummyCookieString = buildCookieString(dummyCookieHeader,
dummyCookieValue, "someurl.com", null, null, null);
cookiesStrings[0] = dummyCookieString;
List<Cookie> result = CookieConverter.getCookies(cookiesStrings,
getUrl(unsecuredUrl + "/someFolder/SomeOtherFolder"));
Assert.assertEquals("Should have 1 cookie", 1, result.size());
Assert.assertEquals("Cookie header should be as defined",
dummyCookieHeader, result.get(0).getName());
Assert.assertEquals("Cookie value should be as defined",
dummyCookieValue, result.get(0).getValue());
}
protected synchronized void clearCookieForHost(String sessionHost) throws Exception {
Cookie sessionCookie = null;
for (Cookie cookie : cookieStore.getCookies()) {
String cookieDomain = cookie.getDomain();
if (cookieDomain != null) {
if (sessionHost.equals(cookieDomain) ||
sessionHost.indexOf(cookieDomain) != -1 ||
cookieDomain.indexOf(sessionHost) != -1)
{
sessionCookie = cookie;
break;
}
}
}
if (sessionCookie != null) {
BasicClientCookie httpCookie =
new BasicClientCookie(sessionCookie.getName(),sessionCookie.getValue());
httpCookie.setExpiryDate(new Date(0));
httpCookie.setVersion(1);
httpCookie.setPath(sessionCookie.getPath());
httpCookie.setDomain(sessionCookie.getDomain());
cookieStore.addCookie(httpCookie);
}
cookieStore.clearExpired(new Date()); // this should clear the cookie
}