下面列出了怎么用java.net.CookieManager的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void shouldStoreCookieWhenPolicyAcceptAll() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ALL))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
public static OkHttpClient getsInstance() {
if (sInstance == null) {
synchronized (OkHttpClientManager.class) {
if (sInstance == null) {
sInstance = new com.squareup.okhttp.OkHttpClient();
// cookie enabled
sInstance.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
// timeout reading data from the host
sInstance.setReadTimeout(15, TimeUnit.SECONDS);
// timeout connection host
sInstance.setConnectTimeout(20, TimeUnit.SECONDS);
}
}
}
return sInstance;
}
private static void assertManagerCookiesMatch(CookieManager cookieManager, String url,
String expectedCookieRequestHeader) throws Exception {
Map<String, List<String>> cookieHeaders =
cookieManager.get(new URI(url), EMPTY_COOKIES_MAP);
if (expectedCookieRequestHeader == null) {
assertTrue(cookieHeaders.isEmpty());
return;
}
assertEquals(1, cookieHeaders.size());
List<String> actualCookieHeaderStrings = cookieHeaders.get("Cookie");
// For simplicity, we concatenate the cookie header strings if there are multiple ones.
String actualCookieRequestHeader = actualCookieHeaderStrings.get(0);
for (int i = 1; i < actualCookieHeaderStrings.size(); i++) {
actualCookieRequestHeader += "; " + actualCookieHeaderStrings.get(i);
}
assertEquals(expectedCookieRequestHeader, actualCookieRequestHeader);
}
protected void setAuthCookieVal(String authCookie, String domain) {
this.authCookie = authCookie;
settings.edit().putString(prefKey, authCookie).apply();
/*
this is technically unnecessary if OkHttp handled the authentication, because it will
have already set the cookies in the CookieHandler. It doesn't seem to cause any issues
just to re-add the cookies, though
*/
HttpCookie httpCookie = new HttpCookie(authCookieKey, authCookie);
httpCookie.setDomain(domain);
try {
CookieStore cookies = ((CookieManager) CookieHandler.getDefault()).getCookieStore();
cookies.add(URI.create(domain), httpCookie);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
cookieHasBeenSet = true;
android.webkit.CookieManager.getInstance().setCookie(domain, httpCookie.getName() + "=" + httpCookie.getValue());
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
android.webkit.CookieManager.getInstance().flush();
} else {
CookieSyncManager.getInstance().sync();
}
}
CookieHttpClientTest() throws Exception {
/* start the server */
ss = new ServerSocket(0);
(new Thread(this)).start();
URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");
// Run without a CookieHandler first
InputStream in = url.openConnection().getInputStream();
while (in.read() != -1); // read response body so connection can be reused
// Set a CookeHandler and retest using the HttpClient from the KAC
CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
in = url.openConnection().getInputStream();
while (in.read() != -1);
if (manager.getCookieStore().getCookies().isEmpty()) {
throw new RuntimeException("Failed: No cookies in the cookie Handler.");
}
}
public void testCookieStoreNullUris() {
CookieStore cookieStore = new CookieManager(createCookieStore(), null).getCookieStore();
HttpCookie cookieA = createCookie("a", "android", ".android.com", "/source");
HttpCookie cookieB = createCookie("b", "banana", "code.google.com", "/p/android");
cookieStore.add(null, cookieA);
assertEquals(Arrays.asList(cookieA), cookieStore.getCookies());
cookieStore.add(null, cookieB);
assertEquals(Arrays.asList(cookieA, cookieB), cookieStore.getCookies());
try {
cookieStore.get(null);
fail();
} catch (NullPointerException expected) {
}
assertEquals(Collections.<URI>emptyList(), cookieStore.getURIs());
assertTrue(cookieStore.remove(null, cookieA));
assertEquals(Arrays.asList(cookieB), cookieStore.getCookies());
assertTrue(cookieStore.removeAll());
assertEquals(Collections.<URI>emptyList(), cookieStore.getURIs());
assertEquals(Collections.<HttpCookie>emptyList(), cookieStore.getCookies());
}
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;
}
CookieHttpClientTest() throws Exception {
/* start the server */
ss = new ServerSocket(0);
(new Thread(this)).start();
URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");
// Run without a CookieHandler first
InputStream in = url.openConnection().getInputStream();
while (in.read() != -1); // read response body so connection can be reused
// Set a CookeHandler and retest using the HttpClient from the KAC
CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
in = url.openConnection().getInputStream();
while (in.read() != -1);
if (manager.getCookieStore().getCookies().isEmpty()) {
throw new RuntimeException("Failed: No cookies in the cookie Handler.");
}
}
private void resetCookie() {
settings.edit().remove(prefKey).apply();
authCookie = "";
try {
/*
This step is *required* for PNA, and nicety for other services. PNA won't let you
log in if you're still holding on to a valid authcookie, so we clear them out.
*/
URI loginURI = URI.create(url.getHost());
CookieStore cookies = ((CookieManager) CookieHandler.getDefault()).getCookieStore();
for (HttpCookie cookie : cookies.get(loginURI)) {
cookies.remove(loginURI, cookie);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
cookieHasBeenSet = false;
}
/**
* Creates an instance of the builder with a base URL and 2 custom builders.
*
* @param httpClientBuilder the builder to build an {@link OkHttpClient}.
* @param retrofitBuilder the builder to build a {@link Retrofit}.
*/
public Builder(OkHttpClient.Builder httpClientBuilder, Retrofit.Builder retrofitBuilder) {
if (httpClientBuilder == null) {
throw new IllegalArgumentException("httpClientBuilder == null");
}
if (retrofitBuilder == null) {
throw new IllegalArgumentException("retrofitBuilder == null");
}
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
customHeadersInterceptor = new CustomHeadersInterceptor();
// Set up OkHttp client
this.httpClientBuilder = httpClientBuilder
.cookieJar(new JavaNetCookieJar(cookieManager))
.readTimeout(120, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.addInterceptor(new RequestIdHeaderInterceptor())
.addInterceptor(new BaseUrlHandler());
this.retrofitBuilder = retrofitBuilder;
this.loggingInterceptor = new LoggingInterceptor(LogLevel.NONE);
this.useHttpClientThreadPool = false;
}
CookieHttpClientTest() throws Exception {
/* start the server */
ss = new ServerSocket(0);
(new Thread(this)).start();
URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");
// Run without a CookieHandler first
InputStream in = url.openConnection().getInputStream();
while (in.read() != -1); // read response body so connection can be reused
// Set a CookeHandler and retest using the HttpClient from the KAC
CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
in = url.openConnection().getInputStream();
while (in.read() != -1);
if (manager.getCookieStore().getCookies().isEmpty()) {
throw new RuntimeException("Failed: No cookies in the cookie Handler.");
}
}
@Override
public HttpRequestImpl response(Response r) throws IOException {
HttpHeaders hdrs = r.headers();
HttpRequestImpl request = r.request();
Exchange<?> e = r.exchange;
Log.logTrace("Response: processing cookies for {0}", request.uri());
Optional<CookieManager> cookieManOpt = e.client().cookieManager();
if (cookieManOpt.isPresent()) {
CookieManager cookieMan = cookieManOpt.get();
Log.logTrace("Response: parsing cookies from {0}", hdrs.map());
cookieMan.put(request.uri(), hdrs.map());
} else {
Log.logTrace("Response: No cookie manager found for {0}",
request.uri());
}
return null;
}
@Test
public void shouldNotStoreCookieWhenPolicyAcceptNone() throws URISyntaxException, IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("https://postman-echo.com/get"))
.GET()
.build();
HttpClient httpClient = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build();
httpClient.send(request, HttpResponse.BodyHandlers.ofString());
assertTrue(httpClient.cookieHandler()
.isPresent());
}
public void testClearingWithMaxAge0() throws Exception {
CookieManager cm = new CookieManager(createCookieStore(), null);
URI uri = URI.create("https://test.com");
Map<String, List<String>> header = new HashMap<>();
List<String> value = new ArrayList<>();
value.add("cookie=1234567890test; domain=.test.com; path=/; " +
"expires=Fri, 31 Dec 9999 04:01:25 GMT-0000");
header.put("Set-Cookie", value);
cm.put(uri, header);
List<HttpCookie> cookies = cm.getCookieStore().getCookies();
assertEquals(1, cookies.size());
value.clear();
header.clear();
value.add("cookie=1234567890test; domain=.test.com; path=/; " +
"max-age=0");
header.put("Set-Cookie", value);
cm.put(uri, header);
cookies = cm.getCookieStore().getCookies();
assertEquals(0, cookies.size());
}
CookieHttpClientTest() throws Exception {
/* start the server */
ss = new ServerSocket(0);
(new Thread(this)).start();
URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");
// Run without a CookieHandler first
InputStream in = url.openConnection().getInputStream();
while (in.read() != -1); // read response body so connection can be reused
// Set a CookeHandler and retest using the HttpClient from the KAC
CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
in = url.openConnection().getInputStream();
while (in.read() != -1);
if (manager.getCookieStore().getCookies().isEmpty()) {
throw new RuntimeException("Failed: No cookies in the cookie Handler.");
}
}
public ApiClient() {
httpClient = new OkHttpClient();
httpClient.setCookieHandler(new CookieManager());
verifyingSsl = true;
json = new JSON();
// Set default User-Agent.
setUserAgent("Swagger-Codegen/6.3.0/java");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("basic", new HttpBasicAuth());
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
addDefaultHeader(CLIENT_HEADER, "SDK-Java");
}
private String loginAndGetFormPostURL()
throws IOException, MalformedURLException, ProtocolException {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpURLConnection conn =
(HttpURLConnection)
new URL(osioAuthEndpoint + "/api/login?redirect=https://che.openshift.io")
.openConnection();
conn.setRequestMethod("GET");
String htmlOutput = IOUtils.toString(conn.getInputStream());
Pattern p = Pattern.compile("action=\"(.*?)\"");
Matcher m = p.matcher(htmlOutput);
if (m.find()) {
String formPostURL = StringEscapeUtils.unescapeHtml(m.group(1));
return formPostURL;
} else {
LOG.error("Unable to login - didn't find URL to send login form to.");
throw new RuntimeException("Unable to login - didn't find URL to send login form to.");
}
}
private OkHttpUtils()
{
mOkHttpClient = new OkHttpClient();
//cookie enabled
mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER));
mDelivery = new Handler(Looper.getMainLooper());
if (true)
{
mOkHttpClient.setHostnameVerifier(new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
});
}
}
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() + "\"");
}
CookieHttpClientTest() throws Exception {
/* start the server */
ss = new ServerSocket(0);
(new Thread(this)).start();
URL url = new URL("http://localhost:" + ss.getLocalPort() +"/");
// Run without a CookieHandler first
InputStream in = url.openConnection().getInputStream();
while (in.read() != -1); // read response body so connection can be reused
// Set a CookeHandler and retest using the HttpClient from the KAC
CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
in = url.openConnection().getInputStream();
while (in.read() != -1);
if (manager.getCookieStore().getCookies().isEmpty()) {
throw new RuntimeException("Failed: No cookies in the cookie Handler.");
}
}
private void testLogIn(URI baseUri, boolean sendPassword)
throws Exception
{
CookieManager cookieManager = new CookieManager();
OkHttpClient client = this.client.newBuilder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
String body = assertOk(client, getLoginHtmlLocation(baseUri))
.orElseThrow(() -> new AssertionError("No response body"));
assertThat(body).contains("action=\"/ui/login\"");
assertThat(body).contains("method=\"post\"");
assertThat(body).doesNotContain("// This value will be replaced");
if (sendPassword) {
assertThat(body).contains("var hidePassword = false;");
}
else {
assertThat(body).contains("var hidePassword = true;");
}
logIn(baseUri, client, sendPassword);
HttpCookie cookie = getOnlyElement(cookieManager.getCookieStore().getCookies());
assertEquals(cookie.getPath(), "/ui");
assertEquals(cookie.getDomain(), baseUri.getHost());
assertEquals(cookie.getMaxAge(), -1);
assertTrue(cookie.isHttpOnly());
assertOk(client, getUiLocation(baseUri));
assertOk(client, getValidApiLocation(baseUri));
assertResponseCode(client, getLocation(baseUri, "/ui/unknown"), SC_NOT_FOUND);
assertResponseCode(client, getLocation(baseUri, "/ui/api/unknown"), SC_NOT_FOUND);
assertRedirect(client, getLogoutLocation(baseUri), getLoginHtmlLocation(baseUri), false);
assertThat(cookieManager.getCookieStore().getCookies()).isEmpty();
}
public void testCookieManagerGet_schemeChecks() throws Exception {
CookieManager cookieManager = new CookieManager(createCookieStore(), null);
cookieManager.put(new URI("http://a.com/"), cookieHeaders("a1=android"));
cookieManager.put(new URI("https://a.com/"), cookieHeaders("a2=android"));
cookieManager.put(new URI("https://a.com/"), cookieHeaders("a3=android; Secure"));
assertManagerCookiesMatch(cookieManager, "http://a.com/", "a1=android; a2=android");
assertManagerCookiesMatch(cookieManager, "https://a.com/",
"a1=android; a2=android; a3=android");
}
public static void main(String[] args) throws IOException, InterruptedException {
/*
HttpClient client = HttpClient.newBuilder()
.cookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_NONE))
.build();
System.out.println(client.cookieHandler().orElseThrow());
*/
CookieManager cm = new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
HttpClient client = HttpClient.newBuilder()
.cookieHandler(cm)
.build();
HttpRequest request = HttpRequest.newBuilder()
.header("Authorization", "Bearer Q3ku4mp_hCQGvAFeYKa0ktFCDKS3VpSA1nwf")
.uri(URI.create("https://gorest.co.in/public-api/users/1"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status code: " + response.statusCode());
System.out.println("\n Body: " + response.body());
System.out.println("\nset-cookie header: " + response.headers().firstValue("set-cookie"));
CookieStore cookieStore = cm.getCookieStore();
System.out.println("\nCookies: " + cookieStore.getCookies());
}
public void testCookieStoreRemoveRequiresUri() throws URISyntaxException {
CookieStore cookieStore = new CookieManager(createCookieStore(), null).getCookieStore();
HttpCookie cookieA = new HttpCookie("a", "android");
cookieStore.add(new URI("http://android.com/source/"), cookieA);
assertFalse("Expected remove() to take the cookie URI into account.", // RI6 fails this
cookieStore.remove(new URI("http://code.google.com/"), cookieA));
assertEquals(Arrays.asList(cookieA), cookieStore.getCookies());
}
public void testPathDefaulting() throws Exception {
TestCookieStore cookieStore = new TestCookieStore();
CookieManager cookieManager = new CookieManager(cookieStore, ACCEPT_ORIGINAL_SERVER);
cookieManager.put(new URI("http://android.com/foo/bar"), cookieHeaders("a=android"));
assertEquals("/foo/", cookieStore.getCookie("a").getPath());
cookieManager.put(new URI("http://android.com/"), cookieHeaders("b=banana"));
assertEquals("/", cookieStore.getCookie("b").getPath());
cookieManager.put(new URI("http://android.com/foo/"), cookieHeaders("c=carrot"));
assertEquals("/foo/", cookieStore.getCookie("c").getPath());
}
void doClientSide() throws Exception {
// Wait for server to get started.
while (!serverReady) {
Thread.sleep(50);
}
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}});
URL url = new URL("https://localhost:" + serverPort +"/");
// Run without a CookieHandler first
InputStream in = url.openConnection().getInputStream();
while (in.read() != -1); // read response body so connection can be reused
// Set a CookeHandler and retest using the HttpClient from the KAC
CookieManager manager = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
in = url.openConnection().getInputStream();
while (in.read() != -1);
if (manager.getCookieStore().getCookies().isEmpty()) {
throw new RuntimeException("Failed: No cookies in the cookie Handler.");
}
}
static void checkCookieNullUri() throws Exception {
//get a cookie store implementation and add a cookie to the store with null URI
CookieStore cookieStore = (new CookieManager()).getCookieStore();
//Check if removeAll() retrurns false on an empty CookieStore
if (cookieStore.removeAll()) {
fail = true;
}
checkFail("removeAll on empty store should return false");
HttpCookie cookie = new HttpCookie("MY_COOKIE", "MY_COOKIE_VALUE");
cookie.setDomain("foo.com");
cookieStore.add(null, cookie);
//Retrieve added cookie
URI uri = new URI("http://foo.com");
List<HttpCookie> addedCookieList = cookieStore.get(uri);
//Verify CookieStore behaves well
if (addedCookieList.size() != 1) {
fail = true;
}
checkFail("Abnormal size of cookie jar");
for (HttpCookie chip : addedCookieList) {
if (!chip.equals(cookie)) {
fail = true;
}
}
checkFail("Cookie not retrieved from Cookie Jar");
boolean ret = cookieStore.remove(null,cookie);
if (!ret) {
fail = true;
}
checkFail("Abnormal removal behaviour from Cookie Jar");
}
public DefaultClientConfiguration(final Properties prop) {
super(prop);
setUncaughtExceptionHandler(new SimpleUncaughtExceptionHandler());
setUiUncaughtExceptionHandler(new SimpleUncaughtExceptionHandler());
setBackgroundExecutor(Executors.newCachedThreadPool(new SimpleDolphinPlatformThreadFactory()));
setCookieStore(new CookieManager().getCookieStore());
setHttpURLConnectionFactory(new DefaultHttpURLConnectionFactory());
}
public void testCookiesWithLeadingPeriod() throws Exception {
CookieManager cm = new CookieManager(createCookieStore(), null);
Map<String, List<String>> responseHeaders = Collections.singletonMap("Set-Cookie",
Collections.singletonList("foo=bar"));
URI uri = new URI("http://chargepoint.com");
cm.put(uri, responseHeaders);
Map<String, List<String>> cookies = cm.get(
new URI("https://webservices.chargepoint.com/backend.php/mobileapi/"),
responseHeaders);
List<String> cookieList = cookies.values().iterator().next();
assertEquals(Collections.singletonList("foo=bar"), cookieList);
}
public void testCookieManagerGet_hostChecks() throws Exception {
CookieManager cookieManager = new CookieManager(createCookieStore(), null);
cookieManager.put(new URI("http://a.com/"), cookieHeaders("a1=android"));
cookieManager.put(new URI("http://b.com/"), cookieHeaders("b1=android"));
assertManagerCookiesMatch(cookieManager, "http://a.com/", "a1=android");
assertManagerCookiesMatch(cookieManager, "http://b.com/", "b1=android");
}