本文整理汇总了Java中java.net.CookieManager类的典型用法代码示例。如果您正苦于以下问题:Java CookieManager类的具体用法?Java CookieManager怎么用?Java CookieManager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
CookieManager类属于java.net包,在下文中一共展示了CookieManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: get
import java.net.CookieManager; //导入依赖的package包/类
public static String get(String requestUrl, CookieManager cookies) throws Exception {
URL url = new URL(urlEncode(requestUrl));
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
if (cookies != null)
applyCookies(connection);
connection.setConnectTimeout(8 * 1000);
connection.setRequestProperty("User-Agent", FrameworkConstants.FRAMEWORK_NAME);
connection.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String text;
StringBuilder result = new StringBuilder();
while ((text = in.readLine()) != null)
result.append(text);
in.close();
storeCookies(connection);
return result.toString();
}
示例2: testSendingCookiesFromStore
import java.net.CookieManager; //导入依赖的package包/类
@Test public void testSendingCookiesFromStore() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
server.start();
HttpUrl serverUrl = urlWithIpAddress(server, "/");
CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
HttpCookie cookieA = new HttpCookie("a", "android");
cookieA.setDomain(serverUrl.host());
cookieA.setPath("/");
cookieManager.getCookieStore().add(serverUrl.uri(), cookieA);
HttpCookie cookieB = new HttpCookie("b", "banana");
cookieB.setDomain(serverUrl.host());
cookieB.setPath("/");
cookieManager.getCookieStore().add(serverUrl.uri(), cookieB);
client = client.newBuilder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
get(serverUrl);
RecordedRequest request = server.takeRequest();
assertEquals("a=android; b=banana", request.getHeader("Cookie"));
}
示例3: receiveAndSendMultipleCookies
import java.net.CookieManager; //导入依赖的package包/类
@Test public void receiveAndSendMultipleCookies() throws Exception {
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse()
.addHeader("Set-Cookie", "a=android")
.addHeader("Set-Cookie", "b=banana"));
server.enqueue(new MockResponse());
server.start();
CookieManager cookieManager = new CookieManager(null, ACCEPT_ORIGINAL_SERVER);
client = client.newBuilder()
.cookieJar(new JavaNetCookieJar(cookieManager))
.build();
get(urlWithIpAddress(server, "/"));
RecordedRequest request1 = server.takeRequest();
assertNull(request1.getHeader("Cookie"));
get(urlWithIpAddress(server, "/"));
RecordedRequest request2 = server.takeRequest();
assertEquals("a=android; b=banana", request2.getHeader("Cookie"));
}
示例4: testCookiesSentIgnoresCase
import java.net.CookieManager; //导入依赖的package包/类
@Test public void testCookiesSentIgnoresCase() throws Exception {
client = client.newBuilder()
.cookieJar(new JavaNetCookieJar(new CookieManager() {
@Override public Map<String, List<String>> get(URI uri,
Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> result = new LinkedHashMap<>();
result.put("COOKIE", Collections.singletonList("Bar=bar"));
result.put("cooKIE2", Collections.singletonList("Baz=baz"));
return result;
}
}))
.build();
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
server.start();
get(server.url("/"));
RecordedRequest request = server.takeRequest();
assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
assertNull(request.getHeader("Cookie2"));
assertNull(request.getHeader("Quux"));
}
示例5: _getClient
import java.net.CookieManager; //导入依赖的package包/类
private static OkHttpClientImpl _getClient(CookieHandler cookieHandler) {
OkHttpClientImpl okHttpClient = new OkHttpClientImpl();
//okHttpClient.setConnectTimeout(SET_CONNECTION_TIMEOUT, TimeUnit.MILLISECONDS);
//okHttpClient.setReadTimeout(SET_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
//okHttpClient.setWriteTimeout(SET_SOCKET_TIMEOUT, TimeUnit.MILLISECONDS);
if (cookieHandler == null) {
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_NONE);
okHttpClient._setCookieHandler(cookieManager);
} else {
okHttpClient._setCookieHandler(cookieHandler);
}
return okHttpClient;
}
示例6: doClientSide
import java.net.CookieManager; //导入依赖的package包/类
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.");
}
}
示例7: CookieHttpClientTest
import java.net.CookieManager; //导入依赖的package包/类
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.");
}
}
示例8: post
import java.net.CookieManager; //导入依赖的package包/类
public static String post(String requestUrl, String payload, CookieManager cookies) throws Exception {
URL url = new URL(urlEncode(requestUrl));
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
if (cookies != null)
applyCookies(connection);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder jsonString = new StringBuilder();
String line;
while ((line = br.readLine()) != null)
jsonString.append(line);
br.close();
connection.disconnect();
storeCookies(connection);
return jsonString.toString();
}
示例9: response
import java.net.CookieManager; //导入依赖的package包/类
@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;
}
示例10: initCookies
import java.net.CookieManager; //导入依赖的package包/类
private void initCookies() {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
if (cookieManager.getCookieStore().getCookies().size() == 0) {
try {
String url = SharedPreferencesEditor.getInstance().getString(
Constants.PREFS_URL_SHORTCUT);
URI uri = new URI(url);
HttpCookie cookie = new HttpCookie(Constants.COOKIE_AUTH_NAME,
SharedPreferencesEditor.getInstance().getString(
Constants.PREFS_AUTH));
cookie.setDomain(uri.getHost());
cookie.setPath(Constants.COOKIE_BASE_PATH);
cookie.setVersion(0);
cookie.setMaxAge((new Date()).getTime()
+ Constants.COOKIE_LIFETIME_YEAR);
cookieManager.getCookieStore().add(uri, cookie);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
示例11: fetchSessionId
import java.net.CookieManager; //导入依赖的package包/类
/**
* <p>It isn't possible to follow
* <a href="https://docs.oracle.com/javase/tutorial/deployment/doingMoreWithRIA/accessingCookies.html">Oracle Accessing Cookies Tutorial</a>
* via default {@link CookieManager} with {@link java.net.InMemoryCookieStore} under the hood.
*
* <p>{@link CookieManager} is the implementation of <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>.
* But the website needs to implement <a href="http://www.ietf.org/rfc/rfc6265.txt">RFC 6265</a>.
*
* <p>RFC 2965: "x.y.com domain-matches .Y.com but not Y.com."<br/>
* RFC 6265: "The domain string is a suffix of the string. The last character of the string that is not included in the domain string is a "." character." <br/>
* Take a look at <a href="https://github.com/square/okhttp/issues/991">OkHttp #991</a>.
*
* <p>So, private {@link com.sun.webkit.network.CookieManager} is implementing RFC 6265, that's why it's using.
*
* @return session id if it exists or {@code null}
*/
@SneakyThrows
private String fetchSessionId() {
Map<String, List<String>> headers = CookieManager.getDefault().get(COOKIE_DOMAIN_URI, new HashMap<>());
List<String> values = headers.getOrDefault("Cookie", new ArrayList<>());
if (values.isEmpty()) {
return null;
}
String headerValue = values.get(0);
String[] cookieEntries = headerValue.split(";");
for (String cookieEntry : cookieEntries) {
String[] cookieParts = cookieEntry.split("=");
if ("remixsid".equals(cookieParts[0].trim())) {
return cookieParts[1].trim();
}
}
return null;
}
示例12: post
import java.net.CookieManager; //导入依赖的package包/类
Call post(Callback callback) throws IOException {
OkHttpClient client = getUnsafeOkHttpClient();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
client.setCookieHandler(cookieManager);
RequestBody requestBody = new FormEncodingBuilder()
.add("user_id", NetId)
.add("user_password", password)
.build();
Request request = new Request.Builder()
.url("https://studentmaintenance.webapps.snu.edu.in/students/public/studentslist/studentslist/loginauth")
.post(requestBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
示例13: LoginService
import java.net.CookieManager; //导入依赖的package包/类
public LoginService() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
mPersistentCookieStore = new PersistentCookieStore(MyApplication.getContextObject());
mClient = new OkHttpClient.Builder()
.cookieJar(new CustomCookieJar(new CookieManager(mPersistentCookieStore, CookiePolicy.ACCEPT_ALL)))
.readTimeout(12, TimeUnit.SECONDS)
.addInterceptor(htmlInterceptor)
.addInterceptor(loggingInterceptor)
.build();
mGson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
.serializeNulls()
.create();
}
示例14: testCookiesSentIgnoresCase
import java.net.CookieManager; //导入依赖的package包/类
@Test public void testCookiesSentIgnoresCase() throws Exception {
client = client.newBuilder()
.cookieJar(new JavaNetCookieJar(new CookieManager() {
@Override public Map<String, List<String>> get(URI uri,
Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> result = new HashMap<>();
result.put("COOKIE", Collections.singletonList("Bar=bar"));
result.put("cooKIE2", Collections.singletonList("Baz=baz"));
return result;
}
}))
.build();
MockWebServer server = new MockWebServer();
server.enqueue(new MockResponse());
server.start();
get(server.url("/"));
RecordedRequest request = server.takeRequest();
assertEquals("Bar=bar; Baz=baz", request.getHeader("Cookie"));
assertNull(request.getHeader("Cookie2"));
assertNull(request.getHeader("Quux"));
}
示例15: tstGetPost
import java.net.CookieManager; //导入依赖的package包/类
public void tstGetPost() throws Exception {
String urlSource = "http://localhost:8080/beige-accounting-web/secure/main.jsp";
String urlBase = urlSource.substring(0, urlSource.indexOf("secure") - 1);
assertEquals("http://localhost:8080/beige-accounting-web", urlBase);
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cookieManager);
URL url = new URL(urlSource);
Map<String, Object> params = new HashMap<String, Object>();
params.put("userName", "admin");
params.put("userPass", "admin");
params.put("authMethod", "form");
params.put("urlBase", urlBase);
params.put("authUrl", urlBase + "/secure/j_security_check");
params.put("authUserName", "j_username");
params.put("authUserPass", "j_password");
params.put("urlSource", urlSource);
tstAuthGet(url, params, cookieManager); //either Get or Post for test allowed
urlSource = "http://localhost:8080/beige-accounting-web/secure/sendEntities";
params.put("urlSource", urlSource);
//url = new URL(urlSource);
//tstAuthPost(url, params, cookieManager);
}