下面列出了怎么用java.net.HttpCookie的API类实例代码及写法,或者点击链接到github查看源代码。
public String resetCookies(List<String> cookieStrings) {
String result = null;
for (String cookieString : cookieStrings) {
List<HttpCookie> parse = HttpCookie.parse(cookieString);
for (HttpCookie httpCookie : parse) {
if(StringUtils.isNoneBlank(httpCookie.getValue())) {
String cookie = httpCookie.getName()+"="+httpCookie.getValue();
if(result==null) {
result = cookie;
} else {
result = result + " ; " + cookie;
}
}
}
}
return result;
}
private List<HttpCookie> getCookiesFromCookiesNode(final Element node)
throws XMLException {
List<HttpCookie> out = new ArrayList<>();
for (int i = 0; i < node.getChildElements().size(); i++) {
Element e = node.getChildElements().get(i);
if(!"cookie".equals(e.getQualifiedName())) {
throw new XMLException("<cookies> element should contain only <cookie> elements");
}
HttpCookie cookie = new HttpCookie(e.getAttributeValue("name"),
e.getAttributeValue("value"));
final String cookieVerStr = e.getAttributeValue("version");
if(StringUtil.isNotEmpty(cookieVerStr)) {
cookie.setVersion(Integer.parseInt(cookieVerStr));
}
else {
cookie.setVersion(CookieVersion.DEFAULT_VERSION.getIntValue());
}
out.add(cookie);
}
return out;
}
/**
* Get all cookies in cookie store, except those have expired
*/
public List<HttpCookie> getCookies() {
List<HttpCookie> rt;
lock.lock();
try {
Iterator<HttpCookie> it = cookieJar.iterator();
while (it.hasNext()) {
if (it.next().hasExpired()) {
it.remove();
}
}
} finally {
rt = Collections.unmodifiableList(cookieJar);
lock.unlock();
}
return rt;
}
@Override
public void add(URI uri, HttpCookie cookie) {
checkInitialization();
mLock.lock();
try {
if (isEnable() && uri != null && cookie != null) {
uri = getEffectiveURI(uri);
if (mCookieStoreListener != null) mCookieStoreListener.onSaveCookie(uri, cookie);
mCookieEntityDao.replace(new CookieEntity(uri, cookie));
trimSize();
}
} finally {
mLock.unlock();
}
}
@Override
public void scanHttpResponseReceive(HttpMessage msg, int id, Source source) {
List<HttpCookie> cookies =
msg.getResponseHeader().getHttpCookies(msg.getRequestHeader().getHostName());
// name of a host from which the response has been sent from
String host = msg.getRequestHeader().getHostName();
// find all loosely scoped cookies
List<HttpCookie> looselyScopedCookies = new LinkedList<HttpCookie>();
for (HttpCookie cookie : cookies) {
if (isLooselyScopedCookie(cookie, host)) {
looselyScopedCookies.add(cookie);
}
}
// raise alert if have found any loosely scoped cookies
if (looselyScopedCookies.size() > 0) {
raiseAlert(msg, id, host, looselyScopedCookies);
}
}
/**
* Get all URIs, which are associated with at least one cookie
* of this cookie store.
*/
public List<URI> getURIs() {
List<URI> uris = new ArrayList<URI>();
lock.lock();
try {
Iterator<URI> it = uriIndex.keySet().iterator();
while (it.hasNext()) {
URI uri = it.next();
List<HttpCookie> cookies = uriIndex.get(uri);
if (cookies == null || cookies.size() == 0) {
// no cookies list or an empty list associated with
// this uri entry, delete it
it.remove();
}
}
} finally {
uris.addAll(uriIndex.keySet());
lock.unlock();
}
return uris;
}
/**
* Add one cookie into cookie store.
*/
public void add(URI uri, HttpCookie cookie) {
// pre-condition : argument can't be null
if (cookie == null) {
throw new NullPointerException("cookie is null");
}
lock.lock();
try {
// remove the ole cookie if there has had one
cookieJar.remove(cookie);
// add new cookie if it has a non-zero max-age
if (cookie.getMaxAge() != 0) {
cookieJar.add(cookie);
// and add it to domain index
addIndex(domainIndex, cookie.getDomain(), cookie);
// add it to uri index, too
addIndex(uriIndex, getEffectiveURI(uri), cookie);
}
} finally {
lock.unlock();
}
storeCookies();
}
/**
* Get all cookies, which:
* 1) given uri domain-matches with, or, associated with
* given uri when added to the cookie store.
* 3) not expired.
* See RFC 2965 sec. 3.3.4 for more detail.
*/
public List<HttpCookie> get(URI uri) {
// argument can't be null
if (uri == null) {
throw new NullPointerException("uri is null");
}
List<HttpCookie> cookies = new ArrayList<HttpCookie>();
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
lock.lock();
try {
// check domainIndex first
getInternal1(cookies, domainIndex, uri.getHost(), secureLink);
// check uriIndex then
getInternal2(cookies, uriIndex, getEffectiveURI(uri), secureLink);
} finally {
lock.unlock();
}
return cookies;
}
/**
* Get all cookies, which:
* 1) given uri domain-matches with, or, associated with
* given uri when added to the cookie store.
* 3) not expired.
* See RFC 2965 sec. 3.3.4 for more detail.
*/
public List<HttpCookie> get(URI uri) {
// argument can't be null
if (uri == null) {
throw new NullPointerException("uri is null");
}
List<HttpCookie> cookies = new ArrayList<>();
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
lock.lock();
try {
// check domainIndex first
getInternal1(cookies, domainIndex, uri.getHost(), secureLink);
// check uriIndex then
getInternal2(cookies, uriIndex, getEffectiveURI(uri), secureLink);
} finally {
lock.unlock();
}
return cookies;
}
/**
* Get all cookies, which:
* 1) given uri domain-matches with, or, associated with
* given uri when added to the cookie store.
* 3) not expired.
* See RFC 2965 sec. 3.3.4 for more detail.
*/
public List<HttpCookie> get(URI uri) {
// argument can't be null
if (uri == null) {
throw new NullPointerException("uri is null");
}
List<HttpCookie> cookies = new ArrayList<HttpCookie>();
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
lock.lock();
try {
// check domainIndex first
getInternal1(cookies, domainIndex, uri.getHost(), secureLink);
// check uriIndex then
getInternal2(cookies, uriIndex, getEffectiveURI(uri), secureLink);
} finally {
lock.unlock();
}
return cookies;
}
/**
* Get all URIs, which are associated with at least one cookie
* of this cookie store.
*/
public List<URI> getURIs() {
List<URI> uris = new ArrayList<URI>();
lock.lock();
try {
Iterator<URI> it = uriIndex.keySet().iterator();
while (it.hasNext()) {
URI uri = it.next();
List<HttpCookie> cookies = uriIndex.get(uri);
if (cookies == null || cookies.size() == 0) {
// no cookies list or an empty list associated with
// this uri entry, delete it
it.remove();
}
}
} finally {
uris.addAll(uriIndex.keySet());
lock.unlock();
}
return uris;
}
/**
* Get all cookies in cookie store, except those have expired
*/
public List<HttpCookie> getCookies() {
List<HttpCookie> rt;
lock.lock();
try {
Iterator<HttpCookie> it = cookieJar.iterator();
while (it.hasNext()) {
if (it.next().hasExpired()) {
it.remove();
}
}
} finally {
rt = Collections.unmodifiableList(cookieJar);
lock.unlock();
}
return rt;
}
/**
* Get all URIs, which are associated with at least one cookie
* of this cookie store.
*/
public List<URI> getURIs() {
List<URI> uris = new ArrayList<URI>();
lock.lock();
try {
Iterator<URI> it = uriIndex.keySet().iterator();
while (it.hasNext()) {
URI uri = it.next();
List<HttpCookie> cookies = uriIndex.get(uri);
if (cookies == null || cookies.size() == 0) {
// no cookies list or an empty list associated with
// this uri entry, delete it
it.remove();
}
}
} finally {
uris.addAll(uriIndex.keySet());
lock.unlock();
}
return uris;
}
/**
* Get all URIs, which are associated with at least one cookie
* of this cookie store.
*/
public List<URI> getURIs() {
List<URI> uris = new ArrayList<URI>();
lock.lock();
try {
Iterator<URI> it = uriIndex.keySet().iterator();
while (it.hasNext()) {
URI uri = it.next();
List<HttpCookie> cookies = uriIndex.get(uri);
if (cookies == null || cookies.size() == 0) {
// no cookies list or an empty list associated with
// this uri entry, delete it
it.remove();
}
}
} finally {
uris.addAll(uriIndex.keySet());
lock.unlock();
}
return uris;
}
/**
* Get all cookies in cookie store, except those have expired
*/
public List<HttpCookie> getCookies() {
List<HttpCookie> rt;
lock.lock();
try {
Iterator<HttpCookie> it = cookieJar.iterator();
while (it.hasNext()) {
if (it.next().hasExpired()) {
it.remove();
}
}
} finally {
rt = Collections.unmodifiableList(cookieJar);
lock.unlock();
}
return rt;
}
public static HttpURLConnection open(URI uri, CookieManager cookieManager) throws Exception {
HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
List<HttpCookie> cookies = cookieManager.getCookieStore().get(uri);
String param = cookies.stream().map(HttpCookie::toString).collect(Collectors.joining("; "));
connection.addRequestProperty("Cookie", param);
return connection;
}
/**
* Get all cookies, which:
* 1) given uri domain-matches with, or, associated with
* given uri when added to the cookie store.
* 3) not expired.
* See RFC 2965 sec. 3.3.4 for more detail.
*/
public List<HttpCookie> get(URI uri) {
// argument can't be null
if (uri == null) {
throw new NullPointerException("uri is null");
}
List<HttpCookie> cookies = new ArrayList<HttpCookie>();
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
lock.lock();
try {
// check domainIndex first
getInternal1(cookies, domainIndex, uri.getHost(), secureLink);
// check uriIndex then
getInternal2(cookies, uriIndex, getEffectiveURI(uri), secureLink);
} finally {
lock.unlock();
}
return cookies;
}
/**
* Get all cookies, which:
* 1) given uri domain-matches with, or, associated with
* given uri when added to the cookie store.
* 3) not expired.
* See RFC 2965 sec. 3.3.4 for more detail.
*/
public List<HttpCookie> get(URI uri) {
// argument can't be null
if (uri == null) {
throw new NullPointerException("uri is null");
}
List<HttpCookie> cookies = new ArrayList<HttpCookie>();
boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
lock.lock();
try {
// check domainIndex first
getInternal1(cookies, domainIndex, uri.getHost(), secureLink);
// check uriIndex then
getInternal2(cookies, uriIndex, getEffectiveURI(uri), secureLink);
} finally {
lock.unlock();
}
return cookies;
}
/**
* Remove a cookie from store
*/
public boolean remove(URI uri, HttpCookie ck) {
// argument can't be null
if (ck == null) {
throw new NullPointerException("cookie is null");
}
boolean modified = false;
lock.lock();
try {
modified = cookieJar.remove(ck);
} finally {
lock.unlock();
}
return modified;
}
@Override
public boolean remove(URI uri, HttpCookie cookie) {
String name = getCookieToken(uri, cookie);
if (mCookieMap.containsKey(uri.getHost()) && mCookieMap.get(uri.getHost()).containsKey(name)) {
mCookieMap.get(uri.getHost()).remove(name);
SharedPreferences.Editor prefsWriter = mCookiePrefs.edit();
if (mCookiePrefs.contains(COOKIE_NAME_PREFIX + name)) {
prefsWriter.remove(COOKIE_NAME_PREFIX + name);
}
prefsWriter.putString(uri.getHost(), TextUtils.join(",", mCookieMap.get(uri.getHost()).keySet()));
prefsWriter.commit();
return true;
} else {
return false;
}
}
@Override
public void remove(HttpCookie httpCookie) {
mLock.lock();
try {
Where.Builder whereBuilder = Where.newBuilder().add(NAME, Where.Options.EQUAL, httpCookie.getName());
String domain = httpCookie.getDomain();
if (!TextUtils.isEmpty(domain)) whereBuilder.and(DOMAIN, Where.Options.EQUAL, domain);
String path = httpCookie.getPath();
if (!TextUtils.isEmpty(path)) {
if (path.length() > 1 && path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
whereBuilder.and(PATH, Where.Options.EQUAL, path);
}
mCookieDao.delete(whereBuilder.build().toString());
} finally {
mLock.unlock();
}
}
public void testSendingCookiesFromStore() throws Exception {
server.enqueue(new MockResponse());
server.play();
CookieManager cookieManager = new CookieManager(createCookieStore(),
ACCEPT_ORIGINAL_SERVER);
HttpCookie cookieA = createCookie("a", "android", server.getCookieDomain(), "/");
cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieA);
HttpCookie cookieB = createCookie("b", "banana", server.getCookieDomain(), "/");
cookieManager.getCookieStore().add(server.getUrl("/").toURI(), cookieB);
CookieHandler.setDefault(cookieManager);
get(server, "/");
RecordedRequest request = server.takeRequest();
List<String> receivedHeaders = request.getHeaders();
assertContains(receivedHeaders, "Cookie: $Version=\"1\"; "
+ "a=\"android\";$Path=\"/\";$Domain=\"" + server.getCookieDomain() + "\"; "
+ "b=\"banana\";$Path=\"/\";$Domain=\"" + server.getCookieDomain() + "\"");
}
protected void onPostExecute(final Boolean success) {
setLoading(false);
if (isCancelled()) return;
if (success) {
showThemeBody(m_ThemeBody);
} else {
getSupportActionBar().setTitle(ex.getMessage());
m_WebView.loadDataWithBaseURL("https://4pda.ru/forum/", m_ThemeBody, "text/html", "UTF-8", null);
AppLog.e(getMainActivity(), ex);
}
CookieSyncManager syncManager = CookieSyncManager.createInstance(m_WebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
for (HttpCookie cookie : Client.getInstance().getCookies()) {
if (cookie.getDomain() != null) {
cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue());
}
//cookieManager.setCookie(cookie.getTitle(),cookie.getValue());
}
syncManager.sync();
}
/**
* Get all URIs, which are associated with at least one cookie
* of this cookie store.
*/
public List<URI> getURIs() {
List<URI> uris = new ArrayList<URI>();
lock.lock();
try {
Iterator<URI> it = uriIndex.keySet().iterator();
while (it.hasNext()) {
URI uri = it.next();
List<HttpCookie> cookies = uriIndex.get(uri);
if (cookies == null || cookies.size() == 0) {
// no cookies list or an empty list associated with
// this uri entry, delete it
it.remove();
}
}
} finally {
uris.addAll(uriIndex.keySet());
lock.unlock();
}
return uris;
}
public void testCookieWithNullPath() throws Exception {
FakeSingleCookieStore fscs = new FakeSingleCookieStore();
CookieManager cm = new CookieManager(fscs, CookiePolicy.ACCEPT_ALL);
HttpCookie cookie = new HttpCookie("foo", "bar");
cookie.setDomain("http://www.foo.com");
cookie.setVersion(0);
fscs.setNextCookie(cookie);
Map<String, List<String>> cookieHeaders = cm.get(
new URI("http://www.foo.com/log/me/in"), Collections.EMPTY_MAP);
List<String> cookies = cookieHeaders.get("Cookie");
assertEquals("foo=bar", cookies.get(0));
}
/**
* Remove a cookie from store
*/
public boolean remove(URI uri, HttpCookie ck) {
// argument can't be null
if (ck == null) {
throw new NullPointerException("cookie is null");
}
boolean modified = false;
lock.lock();
try {
modified = cookieJar.remove(ck);
} finally {
lock.unlock();
}
return modified;
}
/**
* Get all URIs, which are associated with at least one cookie
* of this cookie store.
*/
public List<URI> getURIs() {
List<URI> uris = new ArrayList<URI>();
lock.lock();
try {
Iterator<URI> it = uriIndex.keySet().iterator();
while (it.hasNext()) {
URI uri = it.next();
List<HttpCookie> cookies = uriIndex.get(uri);
if (cookies == null || cookies.size() == 0) {
// no cookies list or an empty list associated with
// this uri entry, delete it
it.remove();
}
}
} finally {
uris.addAll(uriIndex.keySet());
lock.unlock();
}
return uris;
}
default List<HttpCookie> actualCookies(final List<HttpCookie> list) {
Predicate<List<HttpCookie>> addAll = (cookies) -> {
list.addAll(cookies);
return false;
};
traverse(this, ChainedRequest::getParent, ChainedRequest::getCookies, addAll);
return list;
}
private void createCookie(Cookies cookies, String name, String token) {
HttpCookie jwtCookie = new HttpCookie(name, token);
jwtCookie.setSecure(true);
jwtCookie.setHttpOnly(true);
jwtCookie.setVersion(0);
cookies.set(jwtCookie);
}
static void eq(HttpCookie ck1, HttpCookie ck2, boolean same) {
testCount++;
if (ck1.equals(ck2) != same) {
raiseError("Comparison inconsistent: " + ck1 + " " + ck2
+ " should " + (same ? "equal" : "not equal"));
}
int h1 = ck1.hashCode();
int h2 = ck2.hashCode();
if ((h1 == h2) != same) {
raiseError("Comparison inconsistent: hashCode for " + ck1 + " " + ck2
+ " should " + (same ? "equal" : "not equal"));
}
}