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:android.hawkencompanionapp.asynctasks.LoginUserTask.java

private void getUserSession(UserLoginSession userLoginSession) {
    final HttpPost httpPost = new HttpPost(mLoginUrl);
    final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse;//from   w  w w .j a v  a 2s.c o  m

    try {
        Logger.debug(this, "Logging in user: " + userLoginSession.getEmailAddress());
        nameValuePairs.add(new BasicNameValuePair("EmailAddress", userLoginSession.getEmailAddress()));
        nameValuePairs.add(new BasicNameValuePair("Password", userLoginSession.getUserPassword()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpResponse = httpClient.execute(httpPost);

        if (isUserLoginValid(httpResponse)) {
            final List<Cookie> cookies = httpClient.getCookieStore().getCookies();
            Logger.debug(this, cookies.toString());
            userLoginSession.setUserSession(cookies);
            userLoginSession.setUserIsValid();
        }
    } catch (IOException e) {
        Logger.error(this, e.getMessage());
    }
}

From source file:eu.musesproject.client.connectionmanager.HttpConnectionsHelper.java

/**
 * Http post implementation //from ww w  . j a v a2  s.  c  o m
 * @param url
 * @param data
 * @return httpResponse
 * @throws ClientProtocolException
 * @throws IOException
 */

public synchronized HttpResponse doPost(String type, String url, String data)
        throws ClientProtocolException, IOException {
    HttpResponse httpResponse = null;
    HttpPost httpPost = new HttpPost(url);
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    StringEntity s = new StringEntity(data.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/xml");
    httpPost.addHeader("connection-type", type);
    httpPost.setEntity(s);
    httpPost.addHeader("accept", "application/xml");
    if (cookie == null || cookie.isExpired(new Date())) {
        try {
            httpResponse = httpclient.execute(httpPost);
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                Log.d(TAG, "None");
            } else {
                cookie = cookies.get(0);
                cookieExpiryDate = cookie.getExpiryDate();
                Log.d(TAG, "Curent cookie expiry : " + cookieExpiryDate);
            }
        } catch (ClientProtocolException e) {
            Log.d(TAG, e.getMessage());
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }

    } else {
        httpPost.addHeader("accept", "application/xml");
        httpclient.getCookieStore().addCookie(cookie);
        try {
            httpResponse = httpclient.execute(httpPost);
        } catch (ClientProtocolException e) {
            Log.d(TAG, e.getMessage());
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
    }
    return httpResponse;
}

From source file:eu.elf.license.LicenseService.java

/**
 *  Get cookies from admin console//from ww w .  ja  va2s .c o  m
 * @return BasicCookieStore
 */
@SuppressWarnings("deprecation")
public BasicCookieStore getAdminConsoleCookies() {
    //System.out.println("Fetching cookies...");
    //CloseableHttpClient httpclient = HttpClients.createDefault();
    DefaultHttpClient httpclient = new DefaultHttpClient();
    LicenseService.setupProxy(httpclient);
    HttpPost post = new HttpPost(loginUrl + "&username=" + user + "&password=" + pass);

    BasicCookieStore bcs = new BasicCookieStore();

    try {

        HttpResponse response = httpclient.execute(post);
        bcs = (BasicCookieStore) httpclient.getCookieStore();

        //List<Cookie> cookieList = bcs.getCookies();
        //System.out.println("cookieList.size: "+cookieList.size());

        //for (int c = 0; c < cookieList.size(); c++) {
        //System.out.println("cookie "+c);
        //System.out.println(cookieList.get(c).getName());
        //System.out.println(cookieList.get(c).getValue());
        //}

    } catch (ClientProtocolException cpe) {
        cpe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    return bcs;
}

From source file:crow.api.ApiClient.java

/**
 * Api //from w ww .jav  a  2  s.co m
 * 
 * @param request
 * @return
 * @throws ApiException
 */
private final boolean getToCache(T request) throws ApiException {
    // 1.http?
    BasicHttpParams httpParams = new BasicHttpParams();
    // 
    HttpConnectionParams.setConnectionTimeout(httpParams, API_CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, API_SOCKET_TIMEOUT);

    //  Request ?
    Map<String, String> param = makeRequestParam(request);
    StringBuilder basicUrl = new StringBuilder(request.getRequestURL(getApiContext()));
    basicUrl.append("?");
    // ???
    for (Map.Entry<String, String> m : param.entrySet()) {
        basicUrl.append(m.getKey()).append("=").append(m.getValue()).append("&");
    }

    HttpGet httpGet = new HttpGet(basicUrl.toString());
    httpGet.setHeaders(makeRequestHeaders(request));
    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
    try {
        // ??
        HttpResponse httpResponse = httpClient.execute(httpGet);
        // ?
        if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            List<Cookie> cookies = httpClient.getCookieStore().getCookies();
            for (Cookie c : cookies) {
                cookieStore.addCookie(c);
            }
            HttpEntity httpEntity = httpResponse.getEntity();
            InputStream input = httpEntity.getContent();
            return cache.cache(input, request);
        } else {
            throw new ApiException("Api HttpStatusCode:" + httpResponse.getStatusLine().getStatusCode());
        }
    } catch (Exception e) {
        throw new ApiException("Api ?", e);
    }
}

From source file:org.jboss.as.test.integration.web.cookie.CookieUnitTestCase.java

@Test
public void testCookieRetrievedCorrectly() throws Exception {
    log.info("testCookieRetrievedCorrectly()");
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(cookieURL.toURI() + "CookieServlet"));

    // assert that we are able to hit servlet successfully
    int postStatusCode = response.getStatusLine().getStatusCode();
    Header[] postErrorHeaders = response.getHeaders("X-Exception");
    assertTrue("Wrong response code: " + postStatusCode, postStatusCode == HttpURLConnection.HTTP_OK);
    assertTrue("X-Exception(" + Arrays.toString(postErrorHeaders) + ") is null", postErrorHeaders.length == 0);

    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    assertTrue("Sever did not set expired cookie on client", checkNoExpiredCookie(cookies));

    for (Cookie cookie : cookies) {
        log.info("Cookie : " + cookie);
        String cookieName = cookie.getName();
        String cookieValue = cookie.getValue();

        if (cookieName.equals("simpleCookie")) {
            assertTrue("cookie value should be jboss", cookieValue.equals("jboss"));
            assertEquals("cookie path", "/jbosstest-cookie", cookie.getPath());
            assertEquals("cookie persistence", false, cookie.isPersistent());
        } else if (cookieName.equals("withSpace")) {
            assertEquals("should be no quote in cookie with space", cookieValue.indexOf("\""), -1);
        } else if (cookieName.equals("comment")) {
            log.info("comment in cookie: " + cookie.getComment());
            // RFC2109:Note that there is no Comment attribute in the Cookie request header
            // corresponding to the one in the Set-Cookie response header. The user
            // agent does not return the comment information to the origin server.

            assertTrue(cookie.getComment() == null);
        } else if (cookieName.equals("withComma")) {
            assertTrue("should contain a comma", cookieValue.indexOf(",") != -1);
        } else if (cookieName.equals("expireIn10Sec")) {
            Date now = new Date();
            log.info("will sleep for 5 seconds to see if cookie expires");
            assertTrue("cookies should not be expired by now",
                    !cookie.isExpired(new Date(now.getTime() + fiveSeconds)));
            log.info("will sleep for 5 more secs and it should expire");
            assertTrue("cookies should be expired by now",
                    cookie.isExpired(new Date(now.getTime() + 2 * fiveSeconds)));
        }/*  www.  j  a  va  2s . co  m*/
    }
}

From source file:messenger.PlurkApi.java

public String logout() {
    PlurkApi p = PlurkApi.getInstance();
    if (cookiestore == null)
        p.login();//w  w w. ja  v  a  2s.  c om
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpclient.setCookieStore(cookiestore);

    HttpResponse response = null;
    String responseString = null;
    try {
        HttpGet httpget = new HttpGet(getApiUri("/Users/logout?" + "api_key=" + API_KEY));
        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());
            responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
        }
    } 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;
}

From source file:org.opensourcetlapp.tl.TLLib.java

public static boolean login(String login, String pw, Handler handler, Context context) throws IOException {
    handler.sendEmptyMessage(TLHandler.PROGRESS_LOGIN);
    logout();//from   ww w . java  2 s. c om

    // Fetch the token
    HtmlCleaner cleaner = TLLib.buildDefaultHtmlCleaner();
    URL url = new URL(LOGIN_URL);
    //TagNode node = TagNodeFromURLEx2(cleaner, url, handler, context, "<html>", false);
    TagNode node = TLLib.TagNodeFromURLLoginToken(cleaner, url, handler, context);

    String token = null;
    try {
        TagNode result = (TagNode) (node.evaluateXPath("//input")[0]);
        token = result.getAttributeByName("value");
    } catch (XPatherException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    if (token == null) {
        return false;
    }
    // 
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPost httpost = new HttpPost(LOGIN_URL);

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair(USER_FIELD, login));
    nvps.add(new BasicNameValuePair(PASS_FIELD, pw));
    nvps.add(new BasicNameValuePair(REMEMBERME, "1"));
    nvps.add(new BasicNameValuePair("stage", "1"));
    nvps.add(new BasicNameValuePair("back_url", "/"));
    nvps.add(new BasicNameValuePair("token", token));
    Log.d("token:", token);
    tokenField = token;

    if (cookieStore != null) {
        httpclient.setCookieStore(cookieStore);
    }

    try {
        httpost.setEntity(new UrlEncodedFormEntity(nvps));
        HttpResponse response = httpclient.execute(httpost);
        HttpEntity entity = response.getEntity();

        Header[] headers = response.getHeaders("Set-Cookie");
        if (cookieStore.getCookies().size() < 2) {
            loginName = null;
            loginStatus = false;
        } else {
            loginName = login;
            loginStatus = true;
            cookieStore = httpclient.getCookieStore();
        }

        if (entity != null) {
            entity.consumeContent();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return loginStatus;
}

From source file:messenger.PlurkApi.java

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

    HttpGet httpget = new HttpGet(getApiUri("/Users/login?" + "api_key=" + API_KEY + "&" + "username="
            + username + "&" + "password=" + password));
    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());
            responseString = EntityUtils.toString(response.getEntity());
            System.out.println(responseString);
        }
    } 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;
}

From source file:messenger.YahooFinanceAPI.java

public static String httppost(String url, List<NameValuePair> header, String refer, boolean cookie) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (cookie)/*from  w  w  w .  ja v  a2 s  . c om*/
        httpclient.setCookieStore(cookiestore);
    else if (cookiestore1 != null)
        httpclient.setCookieStore(cookiestore1);
    if (use_proxy) {
        HttpHost proxy = new HttpHost(PROXY_NAME, PROXY_PORT);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    HttpPost httpPost = new HttpPost(url);
    httpPost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    Header[] headers = { new BasicHeader("Accept",
            "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"),
            new BasicHeader("Content-Type", "application/x-www-form-urlencoded"),
            new BasicHeader("Origin", "http://aomp.judicial.gov.tw"), new BasicHeader("Referer", refer),
            new BasicHeader("User-Agent",
                    "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.3 (KHTML, like Gecko) Chrome/6.0.472.55 Safari/534.3") };

    httpPost.setHeaders(headers);

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(header, "Big5"));
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    HttpResponse response = null;
    String responseString = null;
    try {
        response = httpclient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            if (cookie)
                cookiestore = httpclient.getCookieStore();
            else
                cookiestore1 = httpclient.getCookieStore();
            responseString = EntityUtils.toString(response.getEntity());
            // pG^O 200 OK ~X
            // System.out.println(responseString);
            //
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header[] urlh = response.getAllHeaders();
            System.out.println(urlh.toString());
        } 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;
}

From source file:org.jboss.as.test.integration.security.loginmodules.AbstractLoginModuleTest.java

protected HttpResponse authAndGetResponse(String URL, String user, String pass) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;//  www  . j a  v  a  2  s.  c  o m
    HttpGet httpget = new HttpGet(URL);

    response = httpclient.execute(httpget);

    HttpEntity entity = response.getEntity();
    if (entity != null)
        EntityUtils.consume(entity);

    // We should get the Login Page
    StatusLine statusLine = response.getStatusLine();
    System.out.println("Login form get: " + statusLine);
    assertEquals(200, statusLine.getStatusCode());

    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

    // We should now login with the user name and password
    HttpPost httpost = new HttpPost(URL + "/j_security_check");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("j_username", user));
    nvps.add(new BasicNameValuePair("j_password", pass));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    response = httpclient.execute(httpost);

    int statusCode = response.getStatusLine().getStatusCode();

    assertTrue((302 == statusCode) || (200 == statusCode));
    // Post authentication - if succesfull, we have a 302 and have to redirect
    if (302 == statusCode) {
        entity = response.getEntity();
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();
        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);
    }

    return response;
}