Java Code Examples for java.net.CookieHandler#setDefault()

The following examples show how to use java.net.CookieHandler#setDefault() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PlayerActivity.java    From leafpicrevived with GNU General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example 2
Source File: OsioKeycloakTestAuthServiceClient.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
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.");
  }
}
 
Example 3
Source File: CookieHttpClientTest.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
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.");
    }
}
 
Example 4
Source File: CookieHttpClientTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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.");
    }
}
 
Example 5
Source File: VideoPlayerActivity.java    From iview-android-tv with MIT License 5 votes vote down vote up
@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);
}
 
Example 6
Source File: CookieHttpsClientTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
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.");
    }
}
 
Example 7
Source File: HttpOnly.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 8
Source File: Resolver.java    From CrappaLinks with GNU General Public License v3.0 5 votes vote down vote up
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;
    }
}
 
Example 9
Source File: UndeployProcessOperation.java    From bonita-studio with GNU General Public License v2.0 5 votes vote down vote up
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);
    }
}
 
Example 10
Source File: HttpOnly.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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);
}
 
Example 11
Source File: JerseyRule.java    From jax-rs-pac4j with Apache License 2.0 5 votes vote down vote up
@Override
protected void before() throws Throwable {
    // Used by Jersey Client to store cookies
    CookieHandler.setDefault(new CookieManager());

    jersey = new MyJerseyTest();
    jersey.setUp();
}
 
Example 12
Source File: CookieHttpsClientTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
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.");
    }
}
 
Example 13
Source File: VideoPlayerActivity.java    From droidkaigi2016 with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 14
Source File: AbstractCookiesTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
     * 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"));
    }
 
Example 15
Source File: HTTPConnection.java    From faveo-helpdesk-android-app with Open Software License 3.0 4 votes vote down vote up
HTTPConnection() {

        CookieManager cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
    }
 
Example 16
Source File: SHelper.java    From Xndroid with GNU General Public License v3.0 4 votes vote down vote up
/**
 * @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);
}
 
Example 17
Source File: MediaPlayerFragment.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
@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);
	}
 
Example 18
Source File: AutoCookieManager.java    From zkspringboot with Apache License 2.0 4 votes vote down vote up
@Override
protected void after() {
	CookieHandler.setDefault(null);
}
 
Example 19
Source File: AbstractNetworkBridge.java    From CrossMobile with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public void initCookies() {
    if (cookies == null)
        CookieHandler.setDefault(cookies = new CookieManagerProxy(initNativeManager()));
}
 
Example 20
Source File: Cloudflare.java    From cloudflare-scrape-Android with MIT License 4 votes vote down vote up
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");
        }


    }
}