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:org.opensourcetlapp.tl.TLLib.java

public static TagNode TagNodeFromURLEx2(HtmlCleaner cleaner, URL url, Handler handler, Context context,
        String fullTag, boolean login) throws IOException {

    handler.sendEmptyMessage(PROGRESS_CONNECTING);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    if (cookieStore != null) {
        httpclient.setCookieStore(cookieStore);
    }/*from  w  w w .  j  a v a  2  s  .c  om*/
    HttpGet httpGet = new HttpGet(url.toExternalForm());
    HttpResponse response = httpclient.execute(httpGet);
    if (cookieStore == null) {
        cookieStore = httpclient.getCookieStore();
    }

    handler.sendEmptyMessage(PROGRESS_DOWNLOADING);
    HttpEntity httpEntity = response.getEntity();
    InputStream is = httpEntity.getContent();
    return TagNodeFromURLHelper(is, fullTag, handler, context, cleaner);
}

From source file:lucee.commons.net.http.httpclient4.HTTPEngine4Impl.java

public static void addCookie(DefaultHttpClient client, String domain, String name, String value, String path,
        String charset) {/*ww  w  .  j  av a 2 s  .  c om*/
    if (ReqRspUtil.needEncoding(name, false))
        name = ReqRspUtil.encode(name, charset);
    if (ReqRspUtil.needEncoding(value, false))
        value = ReqRspUtil.encode(value, charset);
    BasicClientCookie cookie = new BasicClientCookie(name, value);
    if (!StringUtil.isEmpty(domain, true))
        cookie.setDomain(domain);
    if (!StringUtil.isEmpty(path, true))
        cookie.setPath(path);

    client.getCookieStore().addCookie(cookie);
}

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

public static HttpResponse authAndGetResponse(String URL, String user, String pass) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response;//from ww  w . ja va2s. co 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;
}

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

public static void makeCall(String URL, String user, String pass, int expectedStatusCode) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//  w w w. j  a  v  a2 s.  c om
        HttpGet httpget = new HttpGet(URL);

        HttpResponse 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);
        entity = response.getEntity();
        if (entity != null)
            EntityUtils.consume(entity);

        statusLine = response.getStatusLine();

        // Post authentication - we have a 302
        assertEquals(302, statusLine.getStatusCode());
        Header locationHeader = response.getFirstHeader("Location");
        String location = locationHeader.getValue();

        HttpGet httpGet = new HttpGet(location);
        response = httpclient.execute(httpGet);

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

        System.out.println("Post logon cookies:");
        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());
            }
        }

        // Either the authentication passed or failed based on the expected status code
        statusLine = response.getStatusLine();
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.arasthel.almeribus.utils.LoadFromWeb.java

private static int loadCookie() throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpGet get = new HttpGet("http://m.surbus.com/tiempo-espera");
    HttpResponse response = httpClient.execute(get);
    HttpEntity entity = response.getEntity();

    if (entity == null) {
        return ERROR_IO;
    }/*from w w  w  . j  ava2s . c o m*/

    Scanner scan = new Scanner(entity.getContent());
    StringBuilder strBuilder = new StringBuilder();
    while (scan.hasNextLine()) {
        strBuilder.append(scan.nextLine());
    }
    scan.close();
    if (!strBuilder.toString().contains("id=\"blockResult\" class=\"messageResult\"")) {
        return MANTENIMIENTO;
    }

    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    for (Cookie c : cookies) {
        if (c.getName().contains("ASP.NET_SessionId")) {
            cookie = c.getValue();
        }
    }
    return TODO_OK;
}

From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java

public static String get(String url, Cookie[] cookies) {
    String body = null;//from  w w  w.j  a  va  2 s  .  c  o  m
    try {
        StringBuffer buffer = new StringBuffer();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);

        httpClient.setCookieStore(new BasicCookieStore());
        for (int i = 0; i < cookies.length; i++) {
            logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":"
                    + cookies[i].getDomain() + ":" + cookies[i].getPath());
            BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue());
            cookie.setVersion(0);
            URL urlParse = new URL(url);
            String host = urlParse.getHost();
            String domain = null;
            if (host != null && host.indexOf('.') > 0) {
                domain = host.substring(host.indexOf('.') + 1);
            }
            logger.finest("Domain:" + domain);
            cookie.setDomain(domain);
            cookie.setPath("/");

            httpClient.getCookieStore().addCookie(cookie);
        }
        HttpResponse response = httpClient.execute(getRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        logger.finest("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.finest(output);
            buffer.append(output);
        }

        httpClient.getConnectionManager().shutdown();

        body = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return body;
}

From source file:com.ibm.xsp.xflow.activiti.util.HttpClientUtil.java

public static String post(String url, Cookie[] cookies, String content) {
    String body = null;//from  w  w  w  . j av  a 2s.c o m
    try {
        StringBuffer buffer = new StringBuffer();
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost(url);

        StringEntity input = new StringEntity(content);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        httpClient.setCookieStore(new BasicCookieStore());
        String hostName = new URL(url).getHost();
        String domain = hostName.substring(hostName.indexOf("."));
        for (int i = 0; i < cookies.length; i++) {
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest("Cookie:" + cookies[i].getName() + ":" + cookies[i].getValue() + ":"
                        + cookies[i].getDomain() + ":" + cookies[i].getPath());
            }
            BasicClientCookie cookie = new BasicClientCookie(cookies[i].getName(), cookies[i].getValue());
            cookie.setVersion(0);
            cookie.setDomain(domain);
            cookie.setPath("/");

            httpClient.getCookieStore().addCookie(cookie);
        }
        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        if (logger.isLoggable(Level.FINEST)) {
            logger.finest("Output from Server .... \n");
        }
        while ((output = br.readLine()) != null) {
            if (logger.isLoggable(Level.FINEST)) {
                logger.finest(output);
            }
            buffer.append(output);
        }

        httpClient.getConnectionManager().shutdown();

        body = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return body;
}

From source file:com.ibm.sbt.services.client.base.datahandlers.EntityList.java

@Override
public List<Cookie> getCookies() {
    DefaultHttpClient httpClient = (DefaultHttpClient) requestData.getHttpClient();
    return httpClient.getCookieStore().getCookies();
}

From source file:com.josue.lottery.eap.service.core.LotoImporter.java

@Override
@Asynchronous/*from  w  ww . ja  v a 2  s  . com*/
public void importFile() {
    try {

        String urlString = "http://www1.caixa.gov.br/loterias/_arquivos/loterias/D_lotfac.zip";

        DefaultHttpClient client = new DefaultHttpClient();
        CookieStore cookieStore = client.getCookieStore();

        BasicClientCookie cookie = new BasicClientCookie("abc", "123");
        cookie.setDomain("xyz.net");
        cookie.setPath("/");

        cookieStore.addCookie(cookie);
        client.setCookieStore(cookieStore);

        HttpGet request = new HttpGet(urlString);

        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            long len = entity.getContentLength();

            storeFile(entity.getContent());
        }
        System.out.println("### FINISHED ###");
    } catch (IOException ex) {
        logger.error(ex);
    }

}

From source file:org.openehealth.ipf.labs.maven.confluence.export.AbstractConfluenceExportTemplate.java

/**
 * Extracts the JSESSIONID cookie from the HttpMethod
 * //from  www .j  ava2s  .  c  om
 * @param client
 * @return the value of the JSESSIONID cookie
 */
private String extractSessionId(DefaultHttpClient client) throws HttpException {
    for (org.apache.http.cookie.Cookie cookie : client.getCookieStore().getCookies()) {
        if (cookie.getName().equals("JSESSIONID")) {
            return cookie.getValue();
        }
    }
    throw new HttpException("No JSESSIONID found in Set-Cookie response header.");
}