Example usage for org.apache.http.impl.client DefaultHttpClient getCookieStore

List of usage examples for org.apache.http.impl.client DefaultHttpClient getCookieStore

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getCookieStore.

Prototype

public synchronized final CookieStore getCookieStore() 

Source Link

Usage

From source file:com.dajodi.scandic.ScandicSessionHelper.java

public static MemberInfo fetchInfo(String username, String password) throws Exception {
    DefaultHttpClient client = Singleton.INSTANCE.getHttpClient();

    if (!isLoggedIn()) {
        // clear the cookies just to be safe
        client.getCookieStore().clear();
        login(username, password);//from  w  w w . jav  a  2s  .  c o  m
    }

    URI uri = new URI("https://www.scandichotels.com/Frequent-Guest-Programme/");

    HttpGet get = new HttpGet(uri);
    Util.gzipify(get);

    // no redirect please
    final HttpParams params = new BasicHttpParams();
    HttpClientParams.setRedirecting(params, false);
    get.setParams(params);

    HttpResponse response = client.execute(get);

    response = checkSessionStillValid(uri, get, response, username, password);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new ScandicHtmlException("Non-200 response returned for frequent guest page");
    }

    InputStream instream = Util.ungzip(response);

    // should we try to minimize the input stream?
    //        instream = minimizeFormInput(instream, ACCOUNT_DIV_START, ACCOUNT_DIV_END);

    try {
        long before = System.currentTimeMillis();
        MemberInfo memberInfo = Singleton.INSTANCE.getScraper().scrapeMemberInfo(instream);
        Log.d("Scrape member info took " + (System.currentTimeMillis() - before) + "ms");

        return memberInfo;
    } finally {
        instream.close();
    }

}

From source file:fr.mixit.android.utils.NetworkUtils.java

static Cookie getCookie(DefaultHttpClient httpClient) {
    Cookie c = null;//from   www. java2s.c o m
    for (final Cookie cookie : httpClient.getCookieStore().getCookies()) {
        if (cookie != null) {
            c = cookie;
            if (DEBUG_MODE) {
                Log.i("AppInfosFragment", "cookieInfos : "//
                        + "comment:" + cookie.getComment() + //
                        " commentURL:" + cookie.getCommentURL() + //
                        " domain:" + cookie.getDomain() + //
                        " name:" + cookie.getName() + //
                        " path:" + cookie.getPath() + //
                        " value:" + cookie.getValue() + //
                        " version:" + cookie.getVersion() + //
                        " expiryDate:" + cookie.getExpiryDate());
            }
        }
    }

    return c;
}

From source file:net.niyonkuru.koodroid.service.SessionService.java

/**
 * Adds a province cookie to the {@link CookieStore} of the {@link DefaultHttpClient} object. This will stop the
 * Koodo Servers from prompting us with region selection on login.
 *//*from  w  ww.j  av  a  2s . c  o m*/
private static void setProvinceCookie(DefaultHttpClient httpClient) {
    CookieStore cookieStore = httpClient.getCookieStore();

    BasicClientCookie cookie = new BasicClientCookie("prov", "on");
    cookie.setDomain("." + Config.DOMAIN);
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
}

From source file:com.cappuccino.requestframework.CookieManager.java

public static void saveCookie(DefaultHttpClient client) {

    //  /*  ww w  .  j ava2 s  .c  om*/
    if (CookieManager.initialized == false) {
        throw new RuntimeException(" ?");
    }
    if (client == null) {
        throw new IllegalArgumentException();
    }

    //    ? ?
    List<Cookie> cookieList = client.getCookieStore().getCookies();
    if (!cookieList.isEmpty()) {
        //  ? 
        for (Cookie cookie : cookieList) {

            //  sp ? 
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            String cookieDomain = cookie.getDomain();
            // Date cookieExpiryDate = cookie.getExpiryDate();

            application.setCookieName(cookieName);
            application.setCookieValue(cookieValue);
            application.setCookieDomain(cookieDomain);
            // application.setCookieExpiryDate(cookieExpiryDate);

            if (RequestConfig.debuggable() == true) {
                Log.e();
                Log.e("?  ?");
                Log.e(" ? : " + cookieName);
                Log.e("  : " + cookieValue);
                Log.e(" ?? : " + cookieDomain);
            }
        }
    }
}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

public static void executeNoAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
    URL warA1 = new URL(serverA, "/war1/");
    URL warB2 = new URL(serverB + "/war2/");
    URL warB6 = new URL(serverB + "/war6/");

    // Start by accessing the secured index.html of war1
    DefaultHttpClient httpclient = new DefaultHttpClient();

    checkAccessDenied(httpclient, warA1 + "index.html");

    CookieStore store = httpclient.getCookieStore();

    log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));

    // Submit the login form
    executeFormLogin(httpclient, warA1);

    String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
    log.debug("Saw JSESSIONIDSSO=" + ssoID);

    // Now try getting the war2 index using the JSESSIONIDSSO cookie
    log.debug("Prepare /war2/index.html get");
    checkAccessAllowed(httpclient, warB2 + "index.html");

    // Access a secured servlet that calls a secured ejb in war2 to test
    // propagation of the SSO identity to the ejb container.
    checkAccessAllowed(httpclient, warB2 + "EJBServlet");

    // Do the same test on war6 to test SSO auth replication with no auth
    // configured war
    checkAccessAllowed(httpclient, warB6 + "index.html");

    checkAccessAllowed(httpclient, warB2 + "EJBServlet");

}

From source file:org.jboss.as.test.integration.web.sso.SSOTestBase.java

/**
 * Test single sign-on across two web apps using form based auth
 *
 * @throws Exception//ww w .j a  v a2  s .c  o  m
 */
public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
    URL warA1 = new URL(serverA, "/war1/");
    URL warB2 = new URL(serverB, "/war2/");

    // Start by accessing the secured index.html of war1
    DefaultHttpClient httpclient = new DefaultHttpClient();

    checkAccessDenied(httpclient, warA1 + "index.html");

    CookieStore store = httpclient.getCookieStore();

    log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));

    // Submit the login form
    executeFormLogin(httpclient, warA1);

    String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
    log.debug("Saw JSESSIONIDSSO=" + ssoID);

    // Now try getting the war2 index using the JSESSIONIDSSO cookie
    log.debug("Prepare /war2/index.html get");
    checkAccessAllowed(httpclient, warB2 + "index.html");

    // Access a secured servlet that calls a secured ejb in war2 to test
    // propagation of the SSO identity to the ejb container.
    checkAccessAllowed(httpclient, warB2 + "EJBServlet");

    // Now try logging out of war2
    executeLogout(httpclient, warB2);

    // Reset Http client
    httpclient = new DefaultHttpClient();

    // Try accessing war1 again
    checkAccessDenied(httpclient, warA1 + "index.html");

    // Try accessing war2 again
    checkAccessDenied(httpclient, warB2 + "index.html");

}

From source file:fr.mixit.android.utils.NetworkUtils.java

static ResponseHttp getInputStreamFromDefaultHttpClient(String url, boolean isPost, String args) {
    final HttpParams httpParameters = new BasicHttpParams();

    // Set the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, SOCKET_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(httpParameters, BUFFER_SIZE);

    final DefaultHttpClient httpClient = getDefaultHttpClient(httpParameters);

    final ResponseHttp myResponse = new ResponseHttp();

    synchronized (httpClient) {
        if (cookieSession != null) {
            httpClient.getCookieStore().clear();
            httpClient.getCookieStore().addCookie(cookieSession);
        }/*from   www.  ja  va2 s.  co  m*/

        try {
            HttpResponse response = null;

            if (isPost) {
                final HttpPost httpPost = new HttpPost(url);
                if (args != null) {
                    final StringEntity se = new StringEntity(args, HTTP.UTF_8);
                    httpPost.setEntity(se);
                }
                response = httpClient.execute(httpPost);
            } else {
                String urlWithParams = url;
                if (!isPost && args != null) {
                    urlWithParams = getGetURL(url, args);
                }
                final HttpGet httpGet = new HttpGet(urlWithParams);
                response = httpClient.execute(httpGet);
            }

            // Read data if entity is OK
            if (response != null) {
                myResponse.status = response.getStatusLine().getStatusCode();
                if (DEBUG_MODE) {
                    Log.d(TAG, "Status code : " + myResponse.status);
                }
                if (response.getEntity() != null) {
                    myResponse.jsonText = getJson(response.getEntity().getContent());
                }
            }

            cookieSession = getCookie(httpClient);

            // httpClient.getConnectionManager().shutdown();
        } catch (final UnsupportedEncodingException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "UTF8 unsupported", e);
            }
        } catch (final IllegalArgumentException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Invalid URL", e);
            }
        } catch (final ClientProtocolException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Impossible to get data", e);
            }
        } catch (final IllegalStateException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Impossible to read the data", e);
            }
        } catch (final IOException e) {
            if (DEBUG_MODE) {
                Log.e(TAG, "Impossible to get or read the data", e);
            }
        }
    }

    return myResponse;
}

From source file:com.dajodi.scandic.ScandicSessionHelper.java

private static HttpResponse checkSessionStillValid(URI uri, HttpGet get, HttpResponse response, String username,
        String password) throws Exception {
    DefaultHttpClient client = Singleton.INSTANCE.getHttpClient();
    if (response.getStatusLine().getStatusCode() == 302
            && response.getFirstHeader("Location").getValue().toLowerCase().contains("sessionexpired")) {
        // session seems to have expired...
        get.abort();//from  www.java  2s . c o  m

        Log.d("Session seems to have expired, clearing cookies, relogging in");
        client.getCookieStore().clear();
        login(username, password);

        Log.d("Trying to get secure page again");
        get = new HttpGet(uri);
        Util.gzipify(get);
        response = client.execute(get);
    }
    // check the headers, we can assume a few exist for cached requests (save issuing a request for 300k)
    else if (!containsNoCacheHeaders(response)) {
        get.abort();

        Log.d("Session seems to have been hijacked, clearing cookies, relogging in");
        client.getCookieStore().clear();
        login(username, password);

        Log.d("Trying to get secure page again");
        get = new HttpGet(uri);
        Util.gzipify(get);
        response = client.execute(get);
    }

    return response;

}

From source file:org.sharetask.data.IntegrationTest.java

@BeforeClass
public static void login() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpPost httpPost = new HttpPost(BASE_URL + "/user/login");
    httpPost.addHeader(new BasicHeader("Content-Type", "application/json"));
    final StringEntity httpEntity = new StringEntity(
            "{\"username\":\"dev1@shareta.sk\"," + "\"password\":\"password\"}");
    System.out.println(EntityUtils.toString(httpEntity));
    httpPost.setEntity(httpEntity);// w w w  .j  a  v a 2 s  .  c  o  m

    //when
    final HttpResponse response = client.execute(httpPost);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    client.getCookieStore().getCookies();
    for (final Cookie cookie : client.getCookieStore().getCookies()) {
        if (cookie.getName().equals("JSESSIONID")) {
            DOMAIN = cookie.getDomain();
            SESSIONID = cookie.getValue();
        }
    }
}

From source file:messenger.YahooFinanceAPI.java

public static String httpget(String url) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }/*from w ww.j  a  v  a 2 s.  c  o m*/

    HttpGet httpget = new HttpGet(url);
    // Override the default policy for this request

    httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpResponse response = null;
    String responseString = null;
    try {
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            cookiestore = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else {
            System.out.println(response.getStatusLine());
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    httpclient.getConnectionManager().shutdown();
    return responseString;
}