下面列出了java.net.CookieHandler#setDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
updateTheme();
shouldAutoPlay = true;
clearResumePosition();
mediaDataSourceFactory = buildDataSourceFactory(true);
mainHandler = new Handler();
if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
}
setContentView(R.layout.activity_player);
initUi();
rootView = findViewById(R.id.root);
simpleExoPlayerView = findViewById(R.id.player_view);
simpleExoPlayerView.setControllerVisibilityListener(this);
simpleExoPlayerView.requestFocus();
}
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 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.");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EpisodeBaseModel episode = (EpisodeBaseModel) getIntent().getSerializableExtra(ContentManagerBase.CONTENT_ID);
mOtherEpisodeUrls = Arrays.asList(getIntent().getStringArrayExtra(ContentManagerBase.OTHER_EPISODES));
resumePosition = getIntent().getLongExtra(RESUME_POSITION, 0);
if (resumePosition <= 0 && episode.getResumePosition() > 0) {
resumePosition = episode.getResumePosition();
Log.d(TAG, "Resume from recently played");
}
setContentView(R.layout.video_player_activity);
View root = findViewById(R.id.root);
mediaController = new PlaybackControls(this);
mediaController.setAnchorView(root);
videoPlayerView = new VideoPlayerView(this, mediaController, root);
audioCapabilitiesReceiver = new AudioCapabilitiesReceiver(getApplicationContext(), this);
CookieHandler currentHandler = CookieHandler.getDefault();
if (currentHandler != defaultCookieManager) {
CookieHandler.setDefault(defaultCookieManager);
}
playEpisode(episode);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
View root = findViewById(R.id.root);
root.setOnTouchListener((view, motionEvent) -> {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
toggleControlsVisibility();
} else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
view.performClick();
}
return true;
});
root.setOnKeyListener((v, keyCode, event) -> !(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_ESCAPE
|| keyCode == KeyEvent.KEYCODE_MENU) && mediaController.dispatchKeyEvent(event));
shutterView = findViewById(R.id.shutter);
videoFrame = (AspectRatioFrameLayout) findViewById(R.id.video_frame);
surfaceView = (SurfaceView) findViewById(R.id.surface_view);
surfaceView.getHolder().addCallback(this);
subtitleLayout = (SubtitleLayout) findViewById(R.id.subtitles);
mediaController = new KeyCompatibleMediaController(this);
mediaController.setAnchorView(root);
CookieHandler currentHandler = CookieHandler.getDefault();
if (currentHandler != defaultCookieManager) {
CookieHandler.setDefault(defaultCookieManager);
}
audioCapabilitiesReceiver = new AudioCapabilitiesReceiver(this, this);
audioCapabilitiesReceiver.register();
}
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.");
}
}
@Override
protected void before() throws Throwable {
// Used by Jersey Client to store cookies
CookieHandler.setDefault(new CookieManager());
jersey = new MyJerseyTest();
jersey.setUp();
}
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);
}
private void deleteProcessDefinition(final String processLabel, final ProcessAPI processApi, final long processDefinitionId,
final IProgressMonitor monitor)
throws DeletionException, URISyntaxException, IOException {
monitor.subTask(Messages.bind(Messages.deletingProcessDefinition, processLabel));
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
String apiToken = logToSession(monitor);
try {
deleteProcessDefinition(processApi, processDefinitionId,apiToken);
} finally {
logoutFromSession(apiToken);
}
}
protected String doInBackground(String... urls) {
String redirectUrl = urls[0];
// if there's no connection, fail and return the original URL.
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(
Context.CONNECTIVITY_SERVICE);
if (connectivityManager.getActiveNetworkInfo() == null) {
noConnectionError = true;
return redirectUrl;
}
if (useUnshortenIt) {
return getRedirectUsingLongURL(redirectUrl);
} else {
HttpURLConnection.setFollowRedirects(false);
// Use the cookie manager so that cookies are stored. Useful for some hosts that keep
// redirecting us indefinitely unless the set cookie is detected.
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
// Should we resolve all URLs?
boolean resolveAll = true;
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (resolveAllWhen.equals("NEVER") || (resolveAllWhen.equals("WIFI_ONLY") && !wifiInfo.isConnected()))
resolveAll = false;
// Keep trying to resolve the URL until we get a URL that isn't a redirect.
String finalUrl = redirectUrl;
while (redirectUrl != null && ((resolveAll) || (RedirectHelper.isRedirect(Uri.parse(redirectUrl).getHost())))) {
redirectUrl = getRedirect(redirectUrl);
if (redirectUrl != null) {
// This should avoid infinite loops, just in case.
if (redirectUrl.equals(finalUrl))
return finalUrl;
finalUrl = redirectUrl;
}
}
return finalUrl;
}
}
void test(String[] args) throws Exception {
HttpServer server = startHttpServer();
CookieHandler previousHandler = CookieHandler.getDefault();
try {
InetSocketAddress address = server.getAddress();
URI uri = new URI("http://" + InetAddress.getLocalHost().getHostAddress()
+ ":" + address.getPort() + URI_PATH);
populateCookieStore(uri);
doClient(uri);
} finally {
CookieHandler.setDefault(previousHandler);
server.stop(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.");
}
}
private void urlThread(cfCallback callback){
mCookieManager = new CookieManager();
mCookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); //接受所有cookies
CookieHandler.setDefault(mCookieManager);
HttpURLConnection.setFollowRedirects(false);
while (!canVisit){
if (mRetry_count>MAX_COUNT){
break;
}
try {
int responseCode = checkUrl();
if (responseCode==200){
canVisit=true;
break;
}else {
getVisitCookie();
}
} catch (IOException | RuntimeException | InterruptedException e) {
if (mCookieList!=null){
mCookieList= new ArrayList<>(mCookieList);
mCookieList.clear();
}
e.printStackTrace();
} finally {
closeAllConn();
}
mRetry_count++;
}
if (callback!=null){
Looper.prepare();
if (canVisit){
callback.onSuccess(mCookieList,hasNewUrl,mUrl);
}else {
e("Get Cookie Failed");
callback.onFail("Retries exceeded the limit");
}
}
}
@Override
public void initCookies() {
if (cookies == null)
CookieHandler.setDefault(cookies = new CookieManagerProxy(initNativeManager()));
}
/**
* Test which headers show up where. The cookie manager should be notified
* of both user-specified and derived headers like {@code Host}. Headers
* named {@code Cookie} or {@code Cookie2} that are returned by the cookie
* manager should show up in the request and in {@code
* getRequestProperties}.
*/
// TODO(zgao): b/65289980.
// public void testHeadersSentToCookieHandler() throws IOException, InterruptedException {
// final Map<String, List<String>> cookieHandlerHeaders = new HashMap<String, List<String>>();
// CookieHandler.setDefault(new CookieManager(createCookieStore(), null) {
// @Override
// public Map<String, List<String>> get(URI uri,
// Map<String, List<String>> requestHeaders) throws IOException {
// cookieHandlerHeaders.putAll(requestHeaders);
// Map<String, List<String>> result = new HashMap<String, List<String>>();
// result.put("Cookie", Collections.singletonList("Bar=bar"));
// result.put("Cookie2", Collections.singletonList("Baz=baz"));
// result.put("Quux", Collections.singletonList("quux"));
// return result;
// }
// });
// server.enqueue(new MockResponse());
// server.play();
//
// HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
// assertEquals(Collections.<String, List<String>>emptyMap(),
// connection.getRequestProperties());
//
// connection.setRequestProperty("Foo", "foo");
// connection.setDoOutput(true);
// connection.getOutputStream().write(5);
// connection.getOutputStream().close();
// connection.getInputStream().close();
//
// RecordedRequest request = server.takeRequest();
//
// assertContainsAll(cookieHandlerHeaders.keySet(), "Foo");
// assertContainsAll(cookieHandlerHeaders.keySet(),
// "Content-Type", "User-Agent", "Connection", "Host");
// assertFalse(cookieHandlerHeaders.containsKey("Cookie"));
//
// /*
// * The API specifies that calling getRequestProperties() on a connected instance should fail
// * with an IllegalStateException, but the RI violates the spec and returns a valid map.
// * http://www.mail-archive.com/[email protected]/msg01768.html
// */
// try {
// assertContainsAll(connection.getRequestProperties().keySet(), "Foo");
// assertContainsAll(connection.getRequestProperties().keySet(),
// "Content-Type", "Content-Length", "User-Agent", "Connection", "Host");
// assertContainsAll(connection.getRequestProperties().keySet(), "Cookie", "Cookie2");
// assertFalse(connection.getRequestProperties().containsKey("Quux"));
// } catch (IllegalStateException expected) {
// }
//
// assertContainsAll(request.getHeaders(), "Foo: foo", "Cookie: Bar=bar", "Cookie2: Baz=baz");
// assertFalse(request.getHeaders().contains("Quux: quux"));
// }
public void testCookiesSentIgnoresCase() throws Exception {
CookieHandler.setDefault(new CookieManager(createCookieStore(), null) {
@Override public Map<String, List<String>> get(URI uri,
Map<String, List<String>> requestHeaders) throws IOException {
Map<String, List<String>> result = new HashMap<String, List<String>>();
result.put("COOKIE", Collections.singletonList("Bar=bar"));
result.put("cooKIE2", Collections.singletonList("Baz=baz"));
return result;
}
});
server. enqueue(new MockResponse());
server.play();
get(server, "/");
RecordedRequest request = server.takeRequest();
assertContainsAll(request.getHeaders(), "COOKIE: Bar=bar", "cooKIE2: Baz=baz");
assertFalse(request.getHeaders().contains("Quux: quux"));
}
HTTPConnection() {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
}
/**
* @see "http://blogs.sun.com/CoreJavaTechTips/entry/cookie_handling_in_java_se"
*/
public static void enableCookieMgmt() {
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
}
@Override
public void onViewCreated(View v, Bundle savedInstanceState) {
//@Override
//public void onCreate(Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
// if (savedInstanceState != null) {
// shouldAutoPlay = savedInstanceState.getBoolean("shouldAutoPlay");
// }
shouldAutoPlay = true;
clearResumePosition();
mediaDataSourceFactory = buildDataSourceFactory(true);
mainHandler = new Handler();
if (CookieHandler.getDefault() != DEFAULT_COOKIE_MANAGER) {
CookieHandler.setDefault(DEFAULT_COOKIE_MANAGER);
}
//setContentView(R.layout.player_activity);
View rootView = v.findViewById(R.id.root);
rootView.setOnClickListener(this);
debugRootView = (LinearLayout) v.findViewById(R.id.controls_root);
debugTextView = (TextView) v.findViewById(R.id.debug_text_view);
retryButton = (Button) v.findViewById(R.id.retry_button);
retryButton.setOnClickListener(this);
centerInfo = (TextView) v.findViewById(R.id.centerInfo);
// localTime = (TextView) v.findViewById(R.id.localTime);
// battery = (BatteryLevelView) v.findViewById(R.id.battery);
simpleExoPlayerView = (SimpleExoPlayerView) v.findViewById(R.id.player_view);
simpleExoPlayerView.setControllerVisibilityListener(this);
simpleExoPlayerView.requestFocus();
final Intent intent = getActivity().getIntent();
if (intent != null) {
Uri extras = intent.getData();
if (extras != null) {
currentPathTitle = Uri.decode(extras.getPath());
Log.d(TAG, "intent.getData() " + currentPathTitle);
}
}
updateColor(rootView);
}
@Override
protected void after() {
CookieHandler.setDefault(null);
}