下面列出了怎么用java.net.CookiePolicy的API类实例代码及写法,或者点击链接到github查看源代码。
@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());
}
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.");
}
}
@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());
}
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.");
}
}
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.");
}
}
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.");
}
}
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.");
}
}
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.");
}
}
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.");
}
}
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 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;
}
});
}
}
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.");
}
}
/**
* 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.");
}
}
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;
}
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.");
}
}
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 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;
}
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));
}
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.");
}
}
void populateCookieStore(URI uri)
throws IOException {
CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cm);
Map<String,List<String>> header = new HashMap<>();
List<String> values = new ArrayList<>();
values.add("JSESSIONID=" + SESSION_ID + "; version=1; Path="
+ URI_PATH +"; HttpOnly");
values.add("CUSTOMER=WILE_E_COYOTE; version=1; Path=" + URI_PATH);
header.put("Set-Cookie", values);
cm.put(uri, header);
}
/**
* Sets the cookie accept policy for the NSHTTPCookieStorage.
*
* @param cookieAcceptPolicy The cookie accept policy of the
* NSHTTPCookieStorage.
* @see crossmobile.ios.foundation.NSHTTPCookieAcceptPolicy
*/
@CMSetter("@property NSHTTPCookieAcceptPolicy cookieAcceptPolicy;")
public void setCookieAcceptPolicy(int cookieAcceptPolicy) {
this.cookieAcceptPolicy = cookieAcceptPolicy;
Native.network().setCookiePolicy(
cookieAcceptPolicy == NSHTTPCookieAcceptPolicy.Always ? CookiePolicy.ACCEPT_ALL
: (cookieAcceptPolicy == NSHTTPCookieAcceptPolicy.OnlyFromMainDocumentDomain ? CookiePolicy.ACCEPT_ORIGINAL_SERVER
: CookiePolicy.ACCEPT_NONE));
}
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.");
}
}
void populateCookieStore(URI uri)
throws IOException {
CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cm);
Map<String,List<String>> header = new HashMap<>();
List<String> values = new ArrayList<>();
values.add("JSESSIONID=" + SESSION_ID + "; version=1; Path="
+ URI_PATH +"; HttpOnly");
values.add("CUSTOMER=WILE_E_COYOTE; version=1; Path=" + URI_PATH);
header.put("Set-Cookie", values);
cm.put(uri, header);
}
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.");
}
}
void populateCookieStore(URI uri)
throws IOException {
CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cm);
Map<String,List<String>> header = new HashMap<>();
List<String> values = new ArrayList<>();
values.add("JSESSIONID=" + SESSION_ID + "; version=1; Path="
+ URI_PATH +"; HttpOnly");
values.add("CUSTOMER=WILE_E_COYOTE; version=1; Path=" + URI_PATH);
header.put("Set-Cookie", values);
cm.put(uri, header);
}
public static SSOLogin withCredentails(String user, String password) {
Objects.requireNonNull(user, "user must not be null");
Objects.requireNonNull(password, "user must not be null");
SSOLogin ssoLogin = new SSOLogin();
ssoLogin.user = user;
ssoLogin.password = password;
ssoLogin.ssoCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
return ssoLogin;
}
private void initCookieManager() {
// Adapt from ExoPlayer demo app. Start this on demand.
final CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
if(CookieHandler.getDefault() != cookieManager) {
CookieHandler.setDefault(cookieManager);
}
}
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.");
}
}
void populateCookieStore(URI uri)
throws IOException {
CookieManager cm = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cm);
Map<String,List<String>> header = new HashMap<>();
List<String> values = new ArrayList<>();
values.add("JSESSIONID=" + SESSION_ID + "; version=1; Path="
+ URI_PATH +"; HttpOnly");
values.add("CUSTOMER=WILE_E_COYOTE; version=1; Path=" + URI_PATH);
header.put("Set-Cookie", values);
cm.put(uri, header);
}