java.net.CookieHandler#setDefault ( )源码实例Demo

下面列出了java.net.CookieHandler#setDefault ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: leafpicrevived   文件: PlayerActivity.java
@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.");
    }
}
 
源代码3 项目: jdk8u-jdk   文件: CookieHttpClientTest.java
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.");
    }
}
 
源代码4 项目: che   文件: OsioKeycloakTestAuthServiceClient.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.");
  }
}
 
源代码5 项目: iview-android-tv   文件: VideoPlayerActivity.java
@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);
}
 
源代码6 项目: droidkaigi2016   文件: VideoPlayerActivity.java
@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();
}
 
源代码7 项目: jdk8u-dev-jdk   文件: CookieHttpsClientTest.java
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.");
    }
}
 
源代码8 项目: jax-rs-pac4j   文件: JerseyRule.java
@Override
protected void before() throws Throwable {
    // Used by Jersey Client to store cookies
    CookieHandler.setDefault(new CookieManager());

    jersey = new MyJerseyTest();
    jersey.setUp();
}
 
源代码9 项目: openjdk-jdk9   文件: HttpOnly.java
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);
}
 
源代码10 项目: bonita-studio   文件: UndeployProcessOperation.java
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);
    }
}
 
源代码11 项目: CrappaLinks   文件: Resolver.java
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;
    }
}
 
源代码12 项目: jdk8u60   文件: HttpOnly.java
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);
    }
}
 
源代码13 项目: openjdk-jdk8u   文件: CookieHttpsClientTest.java
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.");
    }
}
 
源代码14 项目: cloudflare-scrape-Android   文件: Cloudflare.java
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");
        }


    }
}
 
源代码15 项目: CrossMobile   文件: AbstractNetworkBridge.java
@Override
public void initCookies() {
    if (cookies == null)
        CookieHandler.setDefault(cookies = new CookieManagerProxy(initNativeManager()));
}
 
源代码16 项目: j2objc   文件: AbstractCookiesTest.java
/**
     * 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);
    }
 
源代码18 项目: Xndroid   文件: SHelper.java
/**
 * @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);
}
 
源代码19 项目: PowerFileExplorer   文件: MediaPlayerFragment.java
@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);
	}
 
源代码20 项目: zkspringboot   文件: AutoCookieManager.java
@Override
protected void after() {
	CookieHandler.setDefault(null);
}