Example usage for java.net CookiePolicy ACCEPT_ALL

List of usage examples for java.net CookiePolicy ACCEPT_ALL

Introduction

In this page you can find the example usage for java.net CookiePolicy ACCEPT_ALL.

Prototype

CookiePolicy ACCEPT_ALL

To view the source code for java.net CookiePolicy ACCEPT_ALL.

Click Source Link

Document

One pre-defined policy which accepts all cookies.

Usage

From source file:fi.elfcloud.sci.Connection.java

public Connection(Client client) {
    Connection.client = client;//from w w w  .  java  2s.  c o  m
    Connection.manager = new CookieManager();
    Connection.manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(Connection.manager);
    Connection.cookieJar = manager.getCookieStore();
    Connection.cookies = cookieJar.getCookies();
}

From source file:CookieAccessor.java

/**
 * Get cookies for a url from cookie store
 *///from w ww. j av a  2  s  . c  om
public void getCookieUsingCookieHandler() {
    try {
        // instantiate CookieManager; make sure to set CookiePolicy
        CookieManager manager = new CookieManager();
        manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(manager);

        // get content from URLConnection; cookies are set by web site
        URL url = new URL("http://host.example.com");
        URLConnection connection = url.openConnection();
        connection.getContent();

        // get cookies from underlying CookieStore
        CookieStore cookieJar = manager.getCookieStore();
        List<HttpCookie> cookies = cookieJar.getCookies();
        for (HttpCookie cookie : cookies) {
            System.out.println("CookieHandler retrieved cookie: " + cookie);
        }
    } catch (Exception e) {
        System.out.println("Unable to get cookie using CookieHandler");
        e.printStackTrace();
    }
}

From source file:keywhiz.cli.ClientUtils.java

/**
 * Creates a {@link OkHttpClient} to start a TLS connection.
 *
 * @param cookies list of cookies to include in the client.
 * @return new http client./* w  w w  .  ja  v  a 2s .com*/
 */
public static OkHttpClient sslOkHttpClient(List<HttpCookie> cookies) {
    checkNotNull(cookies);

    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLSv1.2");

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);

        sslContext.init(new KeyManager[0], trustManagerFactory.getTrustManagers(), new SecureRandom());
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw Throwables.propagate(e);
    }

    SSLSocketFactory socketFactory = sslContext.getSocketFactory();

    OkHttpClient client = new OkHttpClient().setSslSocketFactory(socketFactory)
            .setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).setFollowSslRedirects(false);

    client.setRetryOnConnectionFailure(false);
    client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN"));
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookies.forEach(c -> cookieManager.getCookieStore().add(null, c));
    client.setCookieHandler(cookieManager);
    return client;
}

From source file:com.yanzhenjie.nohttp.NoHttp.java

private NoHttp(Config config) {
    mConnectTimeout = config.mConnectTimeout;
    mReadTimeout = config.mReadTimeout;/*from www  .  jav a  2  s  .c o  m*/

    CookieStore cookieStore = config.mCookieStore == null ? new DBCookieStore(NoHttp.getContext())
            : config.mCookieStore;
    mCookieManager = new CookieManager(cookieStore, CookiePolicy.ACCEPT_ALL);
    mCacheStore = config.mCacheStore == null ? new DBCacheStore(NoHttp.getContext()) : config.mCacheStore;
    mNetworkExecutor = config.mNetworkExecutor == null ? new URLConnectionNetworkExecutor()
            : config.mNetworkExecutor;
}

From source file:com.urswolfer.gerrit.client.rest.http.GerritRestClient.java

public GerritRestClient(GerritAuthData authData, HttpRequestExecutor httpRequestExecutor,
        HttpClientBuilderExtension... httpClientBuilderExtensions) {
    this.authData = authData;
    this.httpRequestExecutor = httpRequestExecutor;
    this.httpClientBuilderExtensions = Arrays.asList(httpClientBuilderExtensions);

    cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    cookieStore = cookieManager.getCookieStore();
    loginCache = new LoginCache(authData, cookieStore);
}

From source file:com.yolanda.nohttp.NoHttp.java

/**
 * Initialization NoHttp, Should invoke on {@link Application#onCreate()}.
 *
 * @param application {@link Application}.
 *///from   ww w.j  a  v  a  2 s. c  o m
public static void initialize(Application application) {
    if (sApplication == null) {
        sApplication = application;
        sCookieHandler = new CookieManager(DiskCookieStore.INSTANCE, CookiePolicy.ACCEPT_ALL);
    }
}

From source file:org.oscarehr.integration.excelleris.com.colcamex.www.core.Connect.java

private void _init() {
    CookieManager cookieManager = new CookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);
}

From source file:test.integ.be.fedict.eid.idp.OpenIDTest.java

@Test
public void testOpenID() throws Exception {
    LOG.debug("OpenID integration test");

    // make sure that the session cookies are passed during conversations
    // required to be able to run the Controller here
    MyCookieManager cookieManager = new MyCookieManager();
    cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
    CookieHandler.setDefault(cookieManager);

    // setup//from   w w  w. j a  va  2  s.c  om
    this.servletTester = new ServletTester();
    ServletHolder reqServletHolder = this.servletTester.addServlet(AuthenticationRequestServlet.class,
            "/openid-request");
    reqServletHolder.setInitParameter("ParametersFromRequest", "true");
    reqServletHolder.setInitParameter("SPDestination", "http://localhost/openid-response");
    reqServletHolder.setInitParameter("UserIdentifier", "https://localhost/eid-idp/endpoints/openid-identity");
    reqServletHolder.setInitParameter("TrustServer", "true");

    ServletHolder responseServletHolder = this.servletTester.addServlet(AuthenticationResponseServlet.class,
            "/openid-response");
    responseServletHolder.setInitParameter("RedirectPage", "/target");
    responseServletHolder.setInitParameter("IdentifierSessionAttribute", "identifier");

    this.servletTester.start();
    String location = this.servletTester.createSocketConnector(true);
    LOG.debug("location: " + location);

    HttpState httpState = new HttpState();
    HttpClient httpClient = new HttpClient();
    httpClient.setState(httpState);
    httpClient.getParams()
            .setCookiePolicy(org.apache.commons.httpclient.cookie.CookiePolicy.BROWSER_COMPATIBILITY);
    httpClient.getParams().setParameter("http.protocol.allow-circular-redirects", Boolean.TRUE);

    GetMethod getMethod = new GetMethod(location + "/openid-request?SPDestination=" + location
            + "/openid-response&UserIdentifier=https://localhost/eid-idp/endpoints/openid-identity");
    getMethod.setFollowRedirects(false);

    ProtocolSocketFactory protocolSocketFactory = new MyProtocolSocketFactory();
    Protocol myProtocol = new Protocol("https", protocolSocketFactory, 443);
    Protocol.registerProtocol("https", myProtocol);

    // operate
    int statusCode = httpClient.executeMethod(getMethod);

    // verify
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);
    LOG.debug("response body: " + getMethod.getResponseBodyAsString());
    Header jettySetCookieHeader = getMethod.getResponseHeader("Set-Cookie");
    String jettySessionCookieValue = jettySetCookieHeader.getValue();
    LOG.debug("jetty session cookie value: " + jettySessionCookieValue);

    String idpLocation = getMethod.getResponseHeader("Location").getValue();
    LOG.debug("IdP location: " + idpLocation);
    getMethod = new GetMethod(idpLocation);
    getMethod.setFollowRedirects(false);
    statusCode = httpClient.executeMethod(getMethod);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);
    LOG.debug("response body: " + getMethod.getResponseBodyAsString());

    String idpSessionCookieValue = getMethod.getResponseHeader("Set-Cookie").getValue();
    LOG.debug("IdP session cookie value: " + idpSessionCookieValue);
    String idpSeamLocation = getMethod.getResponseHeader("Location").getValue();
    getMethod = new GetMethod(idpSeamLocation);
    getMethod.setFollowRedirects(false);
    getMethod.addRequestHeader("Cookie", idpSessionCookieValue);
    statusCode = httpClient.executeMethod(getMethod);
    assertEquals(HttpServletResponse.SC_OK, statusCode);
    cookieManager.setSessionCookieValue(idpSessionCookieValue);

    Messages messages = new Messages(Locale.getDefault());
    Runtime runtime = new TestRuntime();
    View view = new TestView();
    Controller controller = new Controller(view, runtime, messages);

    /*
     * Context jettyContext = this.servletTester.getContext();
     * SessionHandler jettySessionHandler =
     * jettyContext.getSessionHandler(); SessionManager jettySessionManager
     * = jettySessionHandler .getSessionManager(); HashSessionManager
     * hashSessionManager = (HashSessionManager) jettySessionManager;
     * LOG.debug("# sessions: " + hashSessionManager.getSessions());
     * assertEquals(1, hashSessionManager.getSessions()); Map<String,
     * HttpSession> sessionMap = hashSessionManager .getSessionMap();
     * LOG.debug("session map: " + sessionMap); HttpSession jettyHttpSession
     * = sessionMap.values().iterator().next(); String jettySessionId =
     * jettyHttpSession.getId(); LOG.debug("jetty HTTP session id: " +
     * jettySessionId);
     */

    // operate
    controller.run();

    // httpState.addCookie(new Cookie("localhost", "JSESSIONID",
    // sessionCookie, "/eid-idp", -1, false));
    // httpClient.setState(httpState);
    LOG.debug("continue to eID IdP exit page...");
    getMethod = new GetMethod("https://localhost/eid-idp/protocol-exit");
    getMethod.addRequestHeader("Cookie", idpSessionCookieValue);
    getMethod.setFollowRedirects(false);
    statusCode = httpClient.executeMethod(getMethod);
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);
    String jettyResponseLocation = getMethod.getResponseHeader("Location").getValue();

    getMethod = new GetMethod(jettyResponseLocation);
    getMethod.setFollowRedirects(false);
    statusCode = httpClient.executeMethod(getMethod);
    LOG.debug("status code: " + statusCode);
    assertEquals(HttpServletResponse.SC_MOVED_TEMPORARILY, statusCode);

    LOG.debug("response body: " + getMethod.getResponseBodyAsString());
}

From source file:org.esupportail.nfctagdroid.NfcTacDroidActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ESUP_NFC_TAG_SERVER_URL = getEsupNfcTagServerUrl(getApplicationContext());
    //To keep session for desfire async requests
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    LocalStorage.getInstance(getApplicationContext());
    Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext()));
    setContentView(R.layout.activity_main);
    mAdapter = NfcAdapter.getDefaultAdapter(this);
    checkHardware(mAdapter);// w w  w .  j a va 2 s .  co m
    localStorageDBHelper = LocalStorage.getInstance(this.getApplicationContext());
    String numeroId = localStorageDBHelper.getValue("numeroId");
    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    String imei = telephonyManager.getDeviceId();
    url = ESUP_NFC_TAG_SERVER_URL + "/nfc-index?numeroId=" + numeroId + "&imei=" + imei + "&macAddress="
            + getMacAddr() + "&apkVersion=" + getApkVersion();
    view = (WebView) this.findViewById(R.id.webView);
    view.clearCache(true);
    view.addJavascriptInterface(new LocalStorageJavaScriptInterface(this.getApplicationContext()),
            "AndroidLocalStorage");
    view.addJavascriptInterface(new AndroidJavaScriptInterface(this.getApplicationContext()), "Android");

    view.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (progress == 100) {
                AUTH_TYPE = localStorageDBHelper.getValue("authType");
            }
        }

        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            log.info("Webview console message : " + consoleMessage.message());
            return false;
        }

    });

    view.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            view.reload();
            return true;
        }
    });
    view.getSettings().setAllowContentAccess(true);
    WebSettings webSettings = view.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webSettings.setDatabaseEnabled(true);
    webSettings.setDatabasePath(this.getFilesDir().getParentFile().getPath() + "/databases/");

    view.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }

    });

    view.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
        }
    });

    view.loadUrl(url);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

From source file:com.intuit.tank.okhttpclient.TankOkHttpClient.java

/**
 * no-arg constructor for OkHttp client/*w  w  w  .  j  a  v a  2  s  .  c o m*/
 */
public TankOkHttpClient() {
    try {

        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };

        // Setup SSL to accept all certs
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, null);
        sslSocketFactory = sslContext.getSocketFactory();

        // Setup Cookie manager
        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
        CookieHandler.setDefault(cookieManager);
        okHttpClient.setCookieHandler(cookieManager);

        okHttpClient.setConnectTimeout(30000, TimeUnit.MILLISECONDS);
        okHttpClient.setReadTimeout(30000, TimeUnit.MILLISECONDS); // Socket-timeout
        okHttpClient.setFollowRedirects(true);
        okHttpClient.setFollowSslRedirects(true);

        okHttpClient.setSslSocketFactory(sslSocketFactory);
        okHttpClient.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }
}