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:fr.eolya.utils.http.HttpLoader.java

public static Map<String, String> getAuthCookies(int authMode, String authLogin, String authPasswd,
        String authParam, String proxyHost, String proxyPort, String proxyExclude, String proxyUser,
        String proxyPassword) {/*from  w  ww. j a  va 2 s  .  c o m*/

    if (authMode == 0)
        return null;

    Map<String, String> authCookies = null;
    String[] aAuthParam = authParam.split("\\|");

    // http://www.java-tips.org/other-api-tips/httpclient/how-to-use-http-cookies.html
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // Proxy
    setProxy(httpClient, aAuthParam[0], proxyHost, proxyPort, proxyExclude, proxyUser, proxyPassword);

    HttpPost httpPost = new HttpPost(aAuthParam[0]);
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    CookieStore cookieStore = new BasicCookieStore();
    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        for (int i = 1; i < aAuthParam.length; i++) {
            String[] aPair = aAuthParam[i].split("=");
            aPair[1] = aPair[1].replaceAll("\\$\\$auth_login\\$\\$", authLogin);
            aPair[1] = aPair[1].replaceAll("\\$\\$auth_passwd\\$\\$", authPasswd);
            nameValuePairs.add(new BasicNameValuePair(aPair[0], aPair[1]));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httpPost.setHeader("ContentType", "application/x-www-form-urlencoded");
        HttpResponse response = httpClient.execute(httpPost, localContext);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.consumeContent();
        }

        List<Cookie> cookies = httpClient.getCookieStore().getCookies();
        if (!cookies.isEmpty()) {
            authCookies = new HashMap<String, String>();
            for (Cookie c : cookies) {
                // TODO: What about the path, the domain ???
                authCookies.put(c.getName(), c.getValue());
            }
        }
        httpPost.abort();
    } catch (ClientProtocolException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
    return authCookies;
}

From source file:crow.api.ApiClient.java

/**
 * Api //  w  w w  . j  a  va 2s. c  om
 * 
 * @param request
 * @return
 * @throws ApiException
 */
private final boolean postToCache(T request) throws ApiException {
    // 1.http?
    BasicHttpParams httpParams = new BasicHttpParams();
    // 
    HttpConnectionParams.setConnectionTimeout(httpParams, API_CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, API_SOCKET_TIMEOUT);

    HttpPost httpPost = new HttpPost(request.getRequestURL(getApiContext()));
    httpPost.setHeaders(makeRequestHeaders(request)); // 

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);

    //  Request ?
    Map<String, String> param = makeRequestParam(request);

    // ???
    ArrayList<BasicNameValuePair> postData = new ArrayList<BasicNameValuePair>();
    for (Map.Entry<String, String> m : param.entrySet()) {
        postData.add(new BasicNameValuePair(m.getKey(), m.getValue()));
    }

    try {
        // ?UTF-8?
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData, PARAM_ENCODING);
        // ?
        httpPost.setEntity(entity);
        // ??
        HttpResponse httpResponse = httpClient.execute(httpPost, localContext);
        // ?
        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:de.mprengemann.hwr.timetabel.data.Parser.java

protected Void doInBackground(Void... params) {
    this.exception = null;

    if (Utils.connectionChecker(context)) {
        try {//w  ww.ja  v  a  2  s  .  c o m
            final String matrikelnr = preferences.getString(context.getString(R.string.prefs_matrikelNrKey),
                    "");

            DefaultHttpClient httpclient = new DefaultHttpClient();
            if (preferences.getBoolean(context.getString(R.string.prefs_proxyFlagKey), false)) {
                HttpHost proxy = new HttpHost(
                        preferences.getString(context.getString(R.string.prefs_proxyKey), "localhost"),
                        Integer.parseInt(
                                preferences.getString(context.getString(R.string.prefs_proxyPortKey), "8080")));
                httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            }

            HttpGet httpget = new HttpGet(Utils.buildURL(context, preferences));

            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                entity.consumeContent();
            }

            List<Cookie> cookies = httpclient.getCookieStore().getCookies();

            HttpPost httpost = new HttpPost("http://ipool.ba-berlin.de/main.php?action=login");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("FORM_LOGIN_NAME", "student"));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_PASS", matrikelnr));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_PAGE", "home"));
            nvps.add(new BasicNameValuePair("FORM_LOGIN_REDIRECTION", Utils.buildURL(context, preferences)));
            nvps.add(new BasicNameValuePair("FORM_ACCEPT", "1"));
            nvps.add(new BasicNameValuePair("LOGIN", "login"));

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

            response = httpclient.execute(httpost);
            entity = response.getEntity();

            if (entity != null) {
                entity.consumeContent();
            }

            cookies = httpclient.getCookieStore().getCookies();

            final URL url;
            InputStream is = null;
            try {
                url = new URL(Utils.buildURL(context, preferences));
                URLConnection c = url.openConnection();

                try {
                    c.setRequestProperty("Cookie", cookies.get(0).getName() + "=" + cookies.get(0).getValue());
                    c.connect();
                    is = c.getInputStream();
                } catch (NullPointerException e) {
                    throw new ConnectionAuthentificationException(
                            context.getString(R.string.dialog_error_message_auth));
                } catch (IndexOutOfBoundsException e) {
                    throw new ConnectionAuthentificationException(
                            context.getString(R.string.dialog_error_message_auth));
                }

                if (is != null) {
                    try {
                        new IcsParser(is, new OnCalendarParsingListener() {

                            @Override
                            public void onNewItem(Component c) {
                                if (c.getName().equals(Component.VEVENT)) {
                                    PropertyList p = c.getProperties();

                                    Subjects s = new Subjects();
                                    s.setTitle(p.getProperty("SUMMARY").getValue());
                                    s.setShortTitle(s.getTitle().substring(s.getTitle().indexOf("-") + 1));
                                    s.setShow(true);

                                    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd HHmmss");

                                    Events evt = new Events();
                                    try {
                                        evt.setStart(df
                                                .parse(p.getProperty("DTSTART").getValue().replace("T", " ")));
                                        evt.setEnd(
                                                df.parse(p.getProperty("DTEND").getValue().replace("T", " ")));
                                    } catch (ParseException e) {
                                        exception = new IPoolFormatException(
                                                context.getString(R.string.dialog_error_message_ipool));
                                        sendBugReport(e, url.toString());
                                    }

                                    evt.setRoom(p.getProperty("LOCATION").getValue());
                                    evt.setUid(p.getProperty("UID").getValue());

                                    String description = p.getProperty("DESCRIPTION").getValue();
                                    evt.setFullDescription(description);
                                    for (String desc : description.split("\\n")) {
                                        if (desc.startsWith("Dozent: ")) {
                                            evt.setLecturer(desc.replace("Dozent: ", ""));
                                            break;
                                        } else if (desc.startsWith("Art: ")) {
                                            evt.setType(desc.replace("Art: ", ""));
                                        }
                                    }
                                    try {
                                        if (listener != null) {
                                            listener.onNewItem(s, evt);
                                        }
                                    } catch (SQLiteConstraintException e) {
                                        exception = new StorageException(
                                                context.getString(R.string.dialog_error_message_storage));
                                        sendBugReport(e, url.toString(), s.toString(), evt.toString());
                                    }

                                }
                            }
                        });
                    } catch (ParserException e) {
                        exception = new UnknownTimetableException(
                                context.getString(R.string.dialog_error_message_auth));
                        sendNewTimetable(url);
                    } catch (IOException e) {
                        if (e instanceof HttpHostConnectException) {
                            exception = new ConnectionTimeoutException(
                                    context.getString(R.string.dialog_error_message_timeout));
                        } else {
                            exception = new ConnectionException(
                                    context.getString(R.string.dialog_error_message));
                        }
                    }
                } else {
                    throw new IOException();
                }
            } catch (ConnectionAuthentificationException e) {
                exception = e;
            } catch (IOException e) {
                if (e instanceof ConnectTimeoutException) {
                    exception = new ConnectionTimeoutException(
                            context.getString(R.string.dialog_error_message_timeout));
                } else if (e instanceof MalformedURLException) {
                    exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                    sendBugReport(e);
                } else if (e instanceof HttpHostConnectException) {
                    exception = new ConnectionTimeoutException(
                            context.getString(R.string.dialog_error_message_timeout));
                } else {
                    exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                    sendBugReport(e);
                }
            } finally {
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (IOException e) {
                    if (e instanceof ConnectTimeoutException) {
                        exception = new ConnectionTimeoutException(
                                context.getString(R.string.dialog_error_message_timeout));
                    } else {
                        exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                        sendBugReport(e);
                    }
                }
            }

            httpclient.getConnectionManager().shutdown();
        } catch (Exception e) {
            if (e instanceof ConnectTimeoutException) {
                exception = new ConnectionTimeoutException(
                        context.getString(R.string.dialog_error_message_timeout));
            } else {
                exception = new ConnectionException(context.getString(R.string.dialog_error_message));
                sendBugReport(e);
            }

        }
    } else {
        exception = new ConnectionException(context.getString(R.string.dialog_error_message));
    }

    return null;
}

From source file:com.thecorpora.qbo.androidapk.RESTClient.java

private int REST_post(String path, String userName, String password) {
    try {/*from  w ww.j av  a  2 s.  com*/
        HttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        // Set the timeout in milliseconds until a connection is established.
        // The default value is zero, that means the timeout is not used. 
        int timeoutConnection = 10000;
        HttpConnectionParams.setConnectionTimeout(httpParams, timeoutConnection);
        // Set the default socket timeout (SO_TIMEOUT) 
        // in milliseconds which is the timeout for waiting for data.
        int timeoutSocket = 10000;
        HttpConnectionParams.setSoTimeout(httpParams, timeoutSocket);

        DefaultHttpClient client = new DefaultHttpClient(httpParams);

        HttpPost post = new HttpPost(path);

        List params = new ArrayList();
        params.add(new BasicNameValuePair("username", userName));
        params.add(new BasicNameValuePair("password", password));

        UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params, HTTP.UTF_8);

        post.setEntity(ent);

        HttpResponse responsePOST = client.execute(post);

        HttpEntity resEntity = responsePOST.getEntity();

        String responseText = EntityUtils.toString(resEntity);

        if (responseText.equalsIgnoreCase("error")) {
            return -1;
        }
        ;

        if (resEntity != null) {
            resEntity.consumeContent();
        }

        System.out.println("Post logon cookies:");
        List<Cookie> cookies = client.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            Log.e(TAG, "No cookies where sent back from server");
            this.setCookie(null);
            return -1;

        } else {
            cookie = cookies.get(0);
            //Save cookie                      
            this.setCookie(cookie.getValue());
            return 0;

        }

    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    }
}

From source file:net.paissad.minus.utils.HttpClientUtils.java

/**
 * /*from w w w  .  j  av  a  2  s .  co  m*/
 * @param baseURL
 * @param parametersBody
 * @param sessionId
 * @param fileToUpload - The file to upload.
 * @param filename - The name of the file to use during the upload process.
 * @return The response received from the Minus API.
 * @throws MinusException
 */
public static MinusHttpResponse doUpload(final String baseURL, final Map<String, String> parametersBody,
        final String sessionId, final File fileToUpload, final String filename) throws MinusException {

    DefaultHttpClient client = null;
    HttpPost uploadRequest = null;
    InputStream responseContent = null;

    try {
        String url = baseURL;
        if (parametersBody != null && !parametersBody.isEmpty()) {
            url += CommonUtils.encodeParams(parametersBody);
        }
        uploadRequest = new HttpPost(url);
        client = new DefaultHttpClient();
        client.setHttpRequestRetryHandler(new MinusHttpRequestRetryHandler());

        FileEntity fileEntity = new FileEntity(fileToUpload, "application/octet-stream");
        uploadRequest.setEntity(fileEntity);

        // We add this headers as specified by the Minus.com API during file
        // upload.
        uploadRequest.addHeader("Content-Disposition", "attachment; filename=a.bin");
        uploadRequest.addHeader("Content-Type", "application/octet-stream");

        client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true);
        client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);

        CookieStore cookieStore = new BasicCookieStore();

        Cookie sessionCookie = null;
        if (sessionId != null && !sessionId.trim().isEmpty()) {
            sessionCookie = new BasicClientCookie2(MINUS_COOKIE_NAME, sessionId);
            ((BasicClientCookie2) sessionCookie).setPath("/");
            ((BasicClientCookie2) sessionCookie).setDomain(MINUS_DOMAIN_NAME);
            ((BasicClientCookie2) sessionCookie).setVersion(0);
            cookieStore.addCookie(sessionCookie);
        }

        client.setCookieStore(cookieStore);
        HttpContext localContext = new BasicHttpContext();
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpResponse httpResponse = client.execute(uploadRequest);

        // Let's update the cookie have the name 'sessionid'
        for (Cookie aCookie : client.getCookieStore().getCookies()) {
            if (aCookie.getName().equals(MINUS_COOKIE_NAME)) {
                sessionCookie = aCookie;
                break;
            }
        }

        StringBuilder result = new StringBuilder();
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK) {
            HttpEntity respEntity = httpResponse.getEntity();
            if (respEntity != null) {
                result.append(EntityUtils.toString(respEntity));
                EntityUtils.consume(respEntity);
            }

        } else {
            // The response code is not OK.
            StringBuilder errMsg = new StringBuilder();
            errMsg.append(" Upload failed => ").append(httpResponse.getStatusLine());
            if (uploadRequest != null) {
                errMsg.append(" : ").append(uploadRequest.getURI());
            }
            throw new MinusException(errMsg.toString());
        }

        return new MinusHttpResponse(result.toString(), sessionCookie);

    } catch (Exception e) {
        if (uploadRequest != null) {
            uploadRequest.abort();
        }
        String errMsg = "Error while uploading file (" + fileToUpload + ") : " + e.getMessage();
        throw new MinusException(errMsg, e);

    } finally {
        if (client != null) {
            client.getConnectionManager().shutdown();
        }
        CommonUtils.closeAllStreamsQuietly(responseContent);
    }
}

From source file:com.domuslink.communication.ApiHandler.java

/**
 * Pull the raw text content of the given URL. This call blocks until the
 * operation has completed, and is synchronized because it uses a shared
 * buffer {@link #sBuffer}./*from w ww  .jav  a 2  s. c o  m*/
 *
 * @param type The type of either a GET or POST for the request
 * @param commandURI The constructed URI for the path
 * @return The raw content returned by the server.
 * @throws ApiException If any connection or server error occurs.
 */
protected static synchronized String urlContent(int type, URI commandURI, ApiCookieHandler cookieHandler)
        throws ApiException {
    HttpResponse response;
    HttpRequestBase request;

    if (sUserAgent == null) {
        throw new ApiException("User-Agent string must be prepared");
    }

    // Create client and set our specific user-agent string
    DefaultHttpClient client = new DefaultHttpClient();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials("", sPassword);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
    client.setCredentialsProvider(credsProvider);
    CookieStore cookieStore = cookieHandler.getCookieStore();
    if (cookieStore != null) {
        boolean expiredCookies = false;
        Date nowTime = new Date();
        for (Cookie theCookie : cookieStore.getCookies()) {
            if (theCookie.isExpired(nowTime))
                expiredCookies = true;
        }
        if (!expiredCookies)
            client.setCookieStore(cookieStore);
        else {
            cookieHandler.setCookieStore(null);
            cookieStore = null;
        }
    }

    try {
        if (type == POST_TYPE)
            request = new HttpPost(commandURI);
        else
            request = new HttpGet(commandURI);

        request.setHeader("User-Agent", sUserAgent);
        response = client.execute(request);

        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            Log.e(TAG,
                    "urlContent: Url issue: " + commandURI.toString() + " with status: " + status.toString());
            throw new ApiException("Invalid response from server: " + status.toString());
        }

        // Pull content stream from response
        HttpEntity entity = response.getEntity();
        InputStream inputStream = entity.getContent();

        ByteArrayOutputStream content = new ByteArrayOutputStream();

        // Read response into a buffered stream
        int readBytes = 0;
        while ((readBytes = inputStream.read(sBuffer)) != -1) {
            content.write(sBuffer, 0, readBytes);
        }

        if (cookieStore == null) {
            List<Cookie> realCookies = client.getCookieStore().getCookies();
            if (!realCookies.isEmpty()) {
                BasicCookieStore newCookies = new BasicCookieStore();
                for (int i = 0; i < realCookies.size(); i++) {
                    newCookies.addCookie(realCookies.get(i));
                    //                      Log.d(TAG, "aCookie - " + realCookies.get(i).toString());
                }
                cookieHandler.setCookieStore(newCookies);
            }
        }

        // Return result from buffered stream
        return content.toString();
    } catch (IOException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } catch (IllegalArgumentException e) {
        Log.e(TAG, "urlContent: client execute: " + commandURI.toString());
        throw new ApiException("Problem communicating with API", e);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        client.getConnectionManager().shutdown();
    }
}

From source file:com.googlecode.noweco.webmail.portal.bull.BullWebmailPortalConnector.java

private String authent(final DefaultHttpClient httpclient, final String user, final String password)
        throws IOException {
    // prepare the request
    HttpPost httpost = new HttpPost("https://bullsentry.bull.net:443/cgi/wway_authent?TdsName=PILX");
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("Internet", "1"));
    nvps.add(new BasicNameValuePair("WebAgt", "1"));
    nvps.add(new BasicNameValuePair("UrlConnect", "https://telemail.bull.fr:443/"));
    nvps.add(new BasicNameValuePair("Service", "WEB-MAIL"));
    nvps.add(new BasicNameValuePair("Action", "go"));
    nvps.add(new BasicNameValuePair("lng", "EN"));
    nvps.add(new BasicNameValuePair("stdport", "80"));
    nvps.add(new BasicNameValuePair("sslport", "443"));
    nvps.add(new BasicNameValuePair("user", user));
    nvps.add(new BasicNameValuePair("cookie", password));
    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    // send the request
    HttpResponse rsp = httpclient.execute(httpost);
    int statusCode = rsp.getStatusLine().getStatusCode();
    if (statusCode != 200) {
        throw new IOException("Unable to connect to bull portail, status code : " + statusCode);
    }/*from www .j av a  2s .co  m*/

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("STEP 1 Authent Cookie : {}", httpclient.getCookieStore().getCookies());
    }

    // free result resources
    HttpEntity entity = rsp.getEntity();
    String firstEntity = EntityUtils.toString(entity);
    if (entity != null) {
        LOGGER.trace("STEP 1 Entity : {}", firstEntity);
        EntityUtils.consume(entity);
    }
    return firstEntity;
}

From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java

@Test
public void testCookieForStateFullClient() throws Exception {
    setAnonymousAccess(false);// w  ww .j  a  v a2 s . c  o  m

    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + "content/";
    URI nexusBaseURI = new URI(url);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "SomeUAThatWillMakeMeLookStateful/1.0");
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // stateful clients must login first, since other rest urls create no sessions
    String loginUrl = this.getBaseNexusUrl() + "service/local/authentication/login";
    assertThat(executeAndRelease(httpClient, new HttpGet(loginUrl), localcontext), equalTo(200));

    // after login check content but make sure only cookie is used
    httpClient.getCredentialsProvider().clear();
    HttpGet getMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200));
    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    assertThat("Session Cookie not set", sessionCookie, notNullValue());
    httpClient.getCookieStore().clear(); // remove cookies

    // do not set the cookie, expect failure
    HttpGet failedGetMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, failedGetMethod, null), equalTo(401));

    // set the cookie expect a 200, If a cookie is set, and cannot be found on the server, the response will fail
    // with a 401
    httpClient.getCookieStore().addCookie(sessionCookie);
    getMethod = new HttpGet(url);
    assertThat(executeAndRelease(httpClient, getMethod, null), equalTo(200));
}

From source file:com.benefit.buy.library.http.query.callback.AbstractAjaxCallback.java

private void getCookie(DefaultHttpClient httpClient) {
    List<Cookie> cookies = httpClient.getCookieStore().getCookies();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < cookies.size(); i++) {
        Cookie cookie = cookies.get(i);//from   www.  j  a  v a 2 s  . c om
        String cookieName = cookie.getName();
        String cookieValue = cookie.getValue();
        if (!TextUtils.isEmpty(cookieName) && !TextUtils.isEmpty(cookieValue)) {
            cookie(cookieName, cookieValue);
            sb.append(cookieName + "=");
            sb.append(cookieValue + ";");
        }
    }
    Log.e("cookie", sb.toString());
}

From source file:org.sonatype.nexus.testsuite.security.nexus4383.Nexus4383LogoutResourceIT.java

/**
 * 1.) Make a get request to set a cookie </BR>
 * 2.) verify cookie works (do not send basic auth) </BR>
 * 3.) do logout  </BR>/*from  w  w  w.ja  v  a 2 s  .  c  o m*/
 * 4.) repeat step 2 and expect failure.
 */
@Test
public void testLogout() throws Exception {
    TestContext context = TestContainer.getInstance().getTestContext();
    String username = context.getAdminUsername();
    String password = context.getPassword();
    String url = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "status";
    String logoutUrl = this.getBaseNexusUrl() + RequestFacade.SERVICE_LOCAL + "authentication/logout";

    Header userAgentHeader = new BasicHeader("User-Agent", "Something Stateful");

    // default useragent is: Jakarta Commons-HttpClient/3.1[\r][\n]
    DefaultHttpClient httpClient = new DefaultHttpClient();
    URI nexusBaseURI = new URI(url);
    final BasicHttpContext localcontext = new BasicHttpContext();
    final HttpHost targetHost = new HttpHost(nexusBaseURI.getHost(), nexusBaseURI.getPort(),
            nexusBaseURI.getScheme());
    httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // HACK: Disable CSRFGuard support for now, its too problematic
    //String owaspQueryParams = null;
    HttpGet getMethod = new HttpGet(url);
    getMethod.addHeader(userAgentHeader);
    try {
        CloseableHttpResponse response = httpClient.execute(getMethod, localcontext);
        // HACK: Disable CSRFGuard support for now, its too problematic
        //Header owaspCsrfToken = response.getFirstHeader("OWASP_CSRFTOKEN");
        //assertThat(owaspCsrfToken, is(notNullValue()));
        //owaspQueryParams = "?" + owaspCsrfToken.getName() + "=" + owaspCsrfToken.getValue();
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies());
    Assert.assertNotNull("Session Cookie not set", sessionCookie);

    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    // now with just the cookie
    httpClient.getCookieStore().addCookie(sessionCookie);
    // HACK: Disable CSRFGuard support for now, its too problematic
    //getMethod = new HttpGet(url + owaspQueryParams);
    getMethod = new HttpGet(url);
    try {
        Assert.assertEquals(httpClient.execute(getMethod).getStatusLine().getStatusCode(), 200);
    } finally {
        getMethod.reset();
    }

    // do logout
    // HACK: Disable CSRFGuard support for now, its too problematic
    //HttpGet logoutGetMethod = new HttpGet(logoutUrl + owaspQueryParams);
    HttpGet logoutGetMethod = new HttpGet(logoutUrl);
    try {
        final HttpResponse response = httpClient.execute(logoutGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 200);
        Assert.assertEquals("OK", EntityUtils.toString(response.getEntity()));
    } finally {
        logoutGetMethod.reset();
    }

    // set cookie again
    httpClient.getCookieStore().clear(); // remove cookies
    httpClient.getCredentialsProvider().clear(); // remove auth

    httpClient.getCookieStore().addCookie(sessionCookie);
    HttpGet failedGetMethod = new HttpGet(url);
    try {
        final HttpResponse response = httpClient.execute(failedGetMethod);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 401);
    } finally {
        failedGetMethod.reset();
    }
}