Example usage for org.apache.http.cookie Cookie getValue

List of usage examples for org.apache.http.cookie Cookie getValue

Introduction

In this page you can find the example usage for org.apache.http.cookie Cookie getValue.

Prototype

String getValue();

Source Link

Document

Returns the value.

Usage

From source file:org.geometerplus.zlibrary.ui.android.network.SQLiteCookieDatabase.java

@Override
protected void saveCookies(List<Cookie> cookies) {
    for (Cookie c : cookies) {
        if (!c.isPersistent()) {
            continue;
        }/*from ww w . ja v a2 s.co m*/
        SQLiteUtil.bindString(myInsertStatement, 1, c.getDomain());
        SQLiteUtil.bindString(myInsertStatement, 2, c.getPath());
        SQLiteUtil.bindString(myInsertStatement, 3, c.getName());
        SQLiteUtil.bindString(myInsertStatement, 4, c.getValue());
        SQLiteUtil.bindDate(myInsertStatement, 5, c.getExpiryDate());
        myInsertStatement.bindLong(6, c.isSecure() ? 1 : 0);
        final long id = myInsertStatement.executeInsert();
        myDeletePortsStatement.bindLong(1, id);
        myDeletePortsStatement.execute();
        if (c.getPorts() != null) {
            myInsertPortsStatement.bindLong(1, id);
            for (int port : c.getPorts()) {
                myInsertPortsStatement.bindLong(2, port);
                myInsertPortsStatement.execute();
            }
        }
    }
}

From source file:net.ecfirm.ec.ec1.net.EcNet.java

protected void setCookie() throws Exception {
    Cookie cookie = null;
    if ((EcNetHelper.cookies != null) && (EcNetHelper.cookies.size() > 0))
        cookie = EcNetHelper.cookies.get(0);
    CookieSyncManager.createInstance(context);
    CookieManager cookieManager = CookieManager.getInstance();
    if (cookie != null) {
        cookieManager.removeSessionCookie();
        String cookieStr = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
        cookieManager.setCookie(net.getProtocol() + "://" + net.getHost(), cookieStr);
        CookieSyncManager.getInstance().sync();
    }//from  ww w.j  a  v a2  s  . c  o m
}

From source file:anhttpclient.AnhttpclientTest.java

@Test
public void testCookies() throws Exception {

    final String cookieName1 = "PREF";
    final String cookieValue1 = "ID=120db22e4e2810cb:FF=0:TM=1318488512:LM=1318488512:S=tTZoDOAsNIbsiH4R";
    final String cookieParams1 = "expires=Sat, 12-Oct-2099 06:48:32 GMT; path=/; domain=localhost";

    final String cookieName2 = "NID";
    final String cookieValue2 = "52=fa8SxaS_YoBUQ7jLIy9bp14biO";
    final String cookieParams2 = "expires=Fri, 13-Apr-2099 06:48:32 GMT; path=/; domain=localhost; HttpOnly";

    final AtomicInteger requestCount = new AtomicInteger(0);

    server.addHandler("/cookies", new ByteArrayHandlerAdapter() {
        public byte[] getResponseAsByteArray(HttpRequestContext httpRequestContext) {
            requestCount.addAndGet(1);//from  w  w  w . j a  v  a 2  s .  c  om

            if (requestCount.get() == 1) {
                setResponseHeader("Set-Cookie", cookieName1 + "=" + cookieValue1 + "; " + cookieParams1,
                        httpRequestContext);
            } else if (requestCount.get() == 2) {
                assertEquals(cookieName1 + "=" + cookieValue1,
                        httpRequestContext.getRequestHeaders().get("Cookie").get(0));
                setResponseHeader("Set-Cookie", cookieName2 + "=" + cookieValue2 + "; " + cookieParams2,
                        httpRequestContext);
            } else {
                //Sends only one cookie somewhy
                //assertEquals(cookieName1 + "; " + cookieName2, httpRequestContext.getRequestHeaders().get("Cookie"));
            }

            return "OK".getBytes();
        }
    });

    WebRequest req = new HttpGetWebRequest(server.getBaseUrl() + "/cookies");
    wb.getResponse(req);
    Cookie cookie1 = wb.getCookieByName(cookieName1);
    assertEquals("Invalid cookie 1", cookieName1, cookie1.getName());
    assertEquals("Invalid cookie 1", cookieValue1, cookie1.getValue());
    wb.getResponse(req);

    cookie1 = wb.getCookieByName(cookieName1);
    assertEquals("Invalid cookie 1", cookieName1, cookie1.getName());
    assertEquals("Invalid cookie 1", cookieValue1, cookie1.getValue());

    Cookie cookie2 = wb.getCookieByName(cookieName2);
    assertEquals("Invalid cookie 2", cookieName2, cookie2.getName());
    assertEquals("Invalid cookie2", cookieValue2, cookie2.getValue());

    wb.getResponse(req);
}

From source file:com.mde.potdroid.helpers.WebsiteInteraction.java

public Boolean login(String password) throws Exception {

    // first, create new user agent
    // and recreate the httpclient
    SecureRandom random = new SecureRandom();
    String uAgent = new BigInteger(50, random).toString(32);
    SharedPreferences.Editor editor = mSettings.edit();
    editor.putString("unique_uagent", uAgent);
    editor.commit();/*www .  j a  va  2  s .c  o  m*/
    mHttpClient = new DefaultHttpClient();
    mHttpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT,
            "Apache-HttpClient/potdroid " + mSettings.getString("unique_uagent", "potdroid"));

    // add login data
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    String username = mSettings.getString("user_name", "");
    if (username.equals("") || password.equals("")) {
        return false;
    }
    nvps.add(new BasicNameValuePair("login_username", username));
    nvps.add(new BasicNameValuePair("login_password", password));
    nvps.add(new BasicNameValuePair("login_lifetime", PotUtils.COOKIE_LIFETIME));

    // create the request
    HttpPost httpost = new HttpPost(PotUtils.LOGIN_URL);
    httpost.setEntity(new UrlEncodedFormEntity(nvps, PotUtils.DEFAULT_ENCODING));

    // execute the form
    HttpResponse response = mHttpClient.execute(httpost);
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), PotUtils.DEFAULT_ENCODING));

    // fetch the result of the http request and save it as a string
    String line;
    StringBuilder sb = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        sb.append(line).append("\n");
    }
    String input = sb.toString();

    // check if the login worked, e.g. one was redirected to SSO.php..
    Pattern pattern = Pattern.compile("http://forum.mods.de/SSO.php\\?UID=([0-9]+)[^']*");
    Matcher m = pattern.matcher(input);

    if (m.find()) {
        // set user id
        editor.putInt("user_id", Integer.valueOf(m.group(1)));
        editor.commit();

        // url for the setcookie found, send a request
        HttpGet cookieUrl = new HttpGet(m.group(0));

        mHttpClient.execute(cookieUrl);

        // store cookie data
        List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("MDESID")) {
                editor.putString("cookie_name", cookie.getName());
                editor.putString("cookie_value", cookie.getValue());
                editor.putString("cookie_url", cookie.getDomain());
                editor.putString("cookie_path", cookie.getPath());
                editor.commit();
            }
        }
        return true;
    }

    return false;
}

From source file:nya.miku.wishmaster.http.cloudflare.CloudflareChecker.java

/**
 *   cloudflare,  cookie/*from ww w .  j a  va  2 s. co  m*/
 * @param exception Cloudflare ?
 * @param httpClient HTTP 
 * @param task ?? 
 * @param challenge challenge 
 * @param recaptchaAnswer   
 * @return ? cookie  null, ?   
 */
public Cookie checkRecaptcha(CloudflareException exception, ExtendedHttpClient httpClient, CancellableTask task,
        String challenge, String recaptchaAnswer) {
    if (!exception.isRecaptcha())
        throw new IllegalArgumentException("wrong type of CloudflareException");
    try {
        recaptchaAnswer = URLEncoder.encode(recaptchaAnswer, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        Logger.e(TAG, e);
    }
    String url = String.format(Locale.US, exception.getCheckCaptchaUrlFormat(), challenge, recaptchaAnswer);
    HttpResponseModel responseModel = null;
    try {
        HttpRequestModel rqModel = HttpRequestModel.builder().setGET().setNoRedirect(false).build();
        CookieStore cookieStore = httpClient.getCookieStore();
        removeCookie(cookieStore, exception.getRequiredCookieName());
        responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
        for (int i = 0; i < 3 && responseModel.statusCode == 400; ++i) {
            Logger.d(TAG, "HTTP 400");
            responseModel.release();
            responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task);
        }
        for (Cookie cookie : cookieStore.getCookies()) {
            if (isClearanceCookie(cookie, url, exception.getRequiredCookieName())) {
                Logger.d(TAG, "Cookie found: " + cookie.getValue());
                return cookie;
            }
        }
        Logger.d(TAG, "Cookie is not found");
    } catch (Exception e) {
        Logger.e(TAG, e);
    } finally {
        if (responseModel != null) {
            responseModel.release();
        }
    }
    return null;
}

From source file:com.capstonecontrol.AccountsActivity.java

/**
 * Retrieves the authorization cookie associated with the given token. This
 * method should only be used when running against a production appengine
 * backend (as opposed to a dev mode server).
 *///from  w ww .  j av  a2s  .  c om
private String getAuthCookie(String authToken) {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        // Get SACSID cookie
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
        String uri = Setup.PROD_URL + "/_ah/login?continue=http://localhost/&auth=" + authToken;
        HttpGet method = new HttpGet(uri);

        HttpResponse res = httpClient.execute(method);
        StatusLine statusLine = res.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        Header[] headers = res.getHeaders("Set-Cookie");
        if (statusCode != 302 || headers.length == 0) {
            return null;
        }

        for (Cookie cookie : httpClient.getCookieStore().getCookies()) {
            if (AUTH_COOKIE_NAME.equals(cookie.getName())) {
                return AUTH_COOKIE_NAME + "=" + cookie.getValue();
            }
        }
    } catch (IOException e) {
        Log.w(TAG, "Got IOException " + e);
        Log.w(TAG, Log.getStackTraceString(e));
    } finally {
        httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
    }

    return null;
}

From source file:com.listomate.activities.AccountsActivity.java

/**
 * Retrieves the authorization cookie associated with the given token. This
 * method should only be used when running against a production appengine
 * backend (as opposed to a dev mode server).
 *//*from w  w w .ja va  2 s  . c o m*/
private String getAuthCookie(String authToken) {
    try {
        // Get SACSID cookie
        DefaultHttpClient client = new DefaultHttpClient();
        String continueURL = Setup.PROD_URL;
        URI uri = new URI(Setup.PROD_URL + "/_ah/login?continue=" + URLEncoder.encode(continueURL, "UTF-8")
                + "&auth=" + authToken);
        HttpGet method = new HttpGet(uri);
        final HttpParams getParams = new BasicHttpParams();
        HttpClientParams.setRedirecting(getParams, false);
        method.setParams(getParams);

        HttpResponse res = client.execute(method);
        Header[] headers = res.getHeaders("Set-Cookie");
        if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
            return null;
        }

        for (Cookie cookie : client.getCookieStore().getCookies()) {
            if (AUTH_COOKIE_NAME.equals(cookie.getName())) {
                return AUTH_COOKIE_NAME + "=" + cookie.getValue();
            }
        }
    } catch (IOException e) {
        Log.w(TAG, "Got IOException " + e);
        Log.w(TAG, Log.getStackTraceString(e));
    } catch (URISyntaxException e) {
        Log.w(TAG, "Got URISyntaxException " + e);
        Log.w(TAG, Log.getStackTraceString(e));
    }

    return null;
}

From source file:com.lillicoder.newsblurry.net.SerializableCookie.java

/**
 *
 * Serialization methods.//from   w  w w . j a  va 2s  . co m
 * 
 */
private void writeObject(ObjectOutputStream out) throws IOException {
    Cookie cookie = this.getCookie();

    // Write all values that can later be restored.
    // This means excluding comment URL, persistence value,
    // and ports.
    out.writeObject(cookie.getComment());
    out.writeObject(cookie.getDomain());
    out.writeObject(cookie.getExpiryDate());
    out.writeObject(cookie.getName());
    out.writeObject(cookie.getPath());
    out.writeObject(cookie.getValue());
    out.writeInt(cookie.getVersion());
    out.writeBoolean(cookie.isSecure());
}

From source file:com.normalexception.app.rx8club.html.LoginFactory.java

/**
 * Report the cookies as a string//  www.  ja  v a2s . c o  m
 * @return   The cookies as a string
 */
public String getCookies() {
    String cStr = "";
    String del = "";
    for (Cookie c : cookieStore.getCookies()) {
        cStr += del + c.getName() + "=" + c.getValue();
        del = ";";
    }
    return cStr;
}

From source file:org.mobicents.servlet.sip.restcomm.dao.mybatis.MybatisHttpCookiesDao.java

private Map<String, Object> toMap(final Sid sid, final Cookie cookie) {
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put("sid", writeSid(sid));
    map.put("comment", cookie.getComment());
    map.put("domain", cookie.getDomain());
    map.put("expiration_date", cookie.getExpiryDate());
    map.put("name", cookie.getName());
    map.put("path", cookie.getPath());
    map.put("value", cookie.getValue());
    map.put("version", cookie.getVersion());
    return map;//from w  w  w .  jav a2s  .  c o  m
}