List of usage examples for org.apache.http.impl.client DefaultHttpClient getCookieStore
public synchronized final CookieStore getCookieStore()
From source file:org.transdroid.search.hdbitsorg.HdBitsOrgAdapter.java
/** * Attempts to log in to hdbits.org with the given credentials. On success * the given DefaultHttpClient should hold all required cookies to access * the site.//from ww w . j ava 2s.c om */ private void login(DefaultHttpClient client, String username, String password, String token) throws Exception { Log.d(LOG_TAG, "Attempting to login."); HttpPost request = new HttpPost(LOGIN_URL); request.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair[] { new BasicNameValuePair(LOGIN_POST_USERNAME, username), new BasicNameValuePair(LOGIN_POST_PASSWORD, password), new BasicNameValuePair(LOGIN_POST_TOKEN, token), new BasicNameValuePair("returnto", "%2F") }))); client.execute(request); // verify we have the cookies needed to log in boolean success = false, uid = false, pass = false, hash = false; for (Cookie cookie : client.getCookieStore().getCookies()) { if ("uid".equals(cookie.getName())) uid = true; if ("pass".equals(cookie.getName())) pass = true; if ("hash".equals(cookie.getName())) hash = true; } // if we don't have the correct cookies, login failed. notify user with a toast and toss an exception. success = uid && pass && hash; if (!success) { Log.e(LOG_TAG, "Failed to log into hdbits.org as '" + username + "'. Did not receive expected login cookies!"); throw new LoginException( "Failed to log into hdbits.org as '" + username + "'. Did not receive expected login cookies!"); } Log.d(LOG_TAG, "Successfully logged in to hdbits.org."); }
From source file:org.brussels.gtug.attendance.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 . j ava 2 s. co m private String getAuthCookie(String authToken) { DefaultHttpClient httpClient = new DefaultHttpClient(); try { // Get SACSID cookie httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); String uri = Constants.APP_SERVER_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.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 w w .j a v a 2 s . co m 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.mingsoft.util.proxy.Proxy.java
/** * post/* ww w .j a v a2 s . c o m*/ * * @param url * ?<br> * @param header * ?Header new Header()<br> * @param params * ?<br> * @param encoding * ??<br> * @return Result */ public static Result post(String url, com.mingsoft.util.proxy.Header header, Map params, String encoding) { //log.info("?" + url); // Httpclient DefaultHttpClient client = new DefaultHttpClient(); // post HttpPost httpPost = new HttpPost(url); // cookie?() httpPost.getParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY); // ???? if (params != null) { List list = new ArrayList(); Iterator it = params.keySet().iterator(); while (it.hasNext()) { String temp = (String) it.next(); list.add(new BasicNameValuePair(temp, params.get(temp) + "")); } try { httpPost.setEntity(new UrlEncodedFormEntity(list, encoding)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); log.error(e.getMessage()); } } // if (null != header && header.getHeaders().size() > 0) { httpPost.setHeaders(Proxy.assemblyHeader(header.getHeaders())); } // HttpResponse response = null; try { response = client.execute(httpPost); HttpEntity entity = response.getEntity(); // // httpPost.abort(); // ?? Result result = new Result(); // ?? result.setStatusCode(response.getStatusLine().getStatusCode()); // ? result.setHeaders(response.getAllHeaders()); // cookie result.setCookie(assemblyCookie(client.getCookieStore().getCookies())); // ? result.setHttpEntity(entity); return result; } catch (ClientProtocolException e) { e.printStackTrace(); log.error(e.getMessage()); } catch (IOException e) { e.printStackTrace(); log.error(e.getMessage()); } 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 .j a va 2s.com 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:es.uma.lcc.lockpic.MainActivity.java
protected Cookie getAuthCookie(String authToken) throws ClientProtocolException, IOException { DefaultHttpClient httpClient = new DefaultHttpClient(); Cookie retCookie = null;/*from www.j av a 2s. c o m*/ String cookieUrl = BASEURL + "/_ah/login?continue=" + URLEncoder.encode(BASEURL, "UTF-8") + "&auth=" + URLEncoder.encode(authToken, "UTF-8"); HttpGet httpget = new HttpGet(cookieUrl); HttpResponse response = httpClient.execute(httpget); if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { if (httpClient.getCookieStore().getCookies().size() > 0) { retCookie = httpClient.getCookieStore().getCookies().get(0); } } // store the cookie SharedPreferences settings = getSharedPreferences(SETTINGS_FILENAME, MODE_PRIVATE); Editor editor = settings.edit(); editor.putString("cookie_value", retCookie.getValue()); editor.putString("cookie_expiry", new SimpleDateFormat("yyyy.MM.dd-HH:mm.ss", Locale.US).format(retCookie.getExpiryDate())); editor.commit(); return retCookie; }
From source file:eu.musesproject.client.connectionmanager.HttpConnectionsHelper.java
/** * POST (HTTPS)// w w w . ja va 2s . c o m * @param url * @param data * @return * @throws ClientProtocolException * @throws IOException */ public HttpResponse doSecurePost(Request request) throws ClientProtocolException, IOException { HttpResponse httpResponse = null; HttpPost httpPost = null; TLSManager tlsManager = new TLSManager(); DefaultHttpClient httpclient = tlsManager.getTLSHttpClient(); if (httpclient != null) { HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT); httpPost = new HttpPost(request.getUrl()); StringEntity s = new StringEntity(request.getData().toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/xml"); httpPost.setEntity(s); httpPost.addHeader("accept", "application/xml"); httpPost.addHeader("connection-type", request.getType()); httpPost.setHeader("poll-interval", getInStringSeconds(request.getPollInterval())); } if (cookie != null && !cookie .isExpired(new Date()) /*!isSessionExpired(new Date(), AlarmReceiver.LAST_SENT_POLL_INTERVAL)*/) { httpclient.getCookieStore().addCookie(cookie); try { httpResponse = httpclient.execute(httpPost); } catch (ClientProtocolException e) { Log.d(TAG, e.getMessage()); } catch (IOException e) { Log.d(TAG, e.getMessage()); } } else { try { httpResponse = httpclient.execute(httpPost); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookie = cookies.get(0); } } catch (ClientProtocolException e) { Log.d(TAG, e.getMessage()); } catch (IOException e) { Log.d(TAG, e.getMessage()); } } AlarmReceiver.LAST_SENT_POLL_INTERVAL = Integer.parseInt(request.getPollInterval()); return httpResponse; }
From source file:org.sonatype.nexus.testsuite.security.nexus4257.Nexus4257CookieVerificationIT.java
/** * Makes a request after setting the user agent and verifies that the session cookie is NOT set. *//* w w w . jav a 2 s .c o m*/ private void testCookieNotSetForKnownStateLessClients(final String userAgent) throws Exception { TestContext context = TestContainer.getInstance().getTestContext(); String username = context.getAdminUsername(); String password = context.getPassword(); String url = this.getBaseNexusUrl() + "content/"; URI uri = new URI(url); Header header = new BasicHeader("User-Agent", userAgent + "/1.6"); // user agent plus some version DefaultHttpClient httpClient = new DefaultHttpClient(); final BasicHttpContext localcontext = new BasicHttpContext(); final HttpHost targetHost = new HttpHost(uri.getHost(), uri.getPort(), uri.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); HttpGet getMethod = new HttpGet(url); getMethod.addHeader(header); assertThat(executeAndRelease(httpClient, getMethod, localcontext), equalTo(200)); Cookie sessionCookie = this.getSessionCookie(httpClient.getCookieStore().getCookies()); assertThat("Session Cookie should not be set for user agent: " + userAgent, sessionCookie, nullValue()); }
From source file:com.nimbits.user.GoogleAuthentication.java
private Cookie getAuthCookie(final String gaeAppBaseUrl, final String gaeAppLoginUrl, final String authToken) throws NimbitsException { final DefaultHttpClient httpClient = new DefaultHttpClient(); Cookie retObj = null;/*www . ja v a2 s.c o m*/ final String cookieUrl; try { cookieUrl = gaeAppLoginUrl + "?continue=" + URLEncoder.encode(gaeAppBaseUrl, Const.CONST_ENCODING) + "&auth=" + URLEncoder.encode(authToken, Const.CONST_ENCODING); // // String cookieUrl = gaeAppLoginUrl + "?continue=" // + URLEncoder.encode(gaeAppBaseUrl,Const.CONST_ENCODING) + "&auth=" + authToken; //httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); final HttpGet httpget = new HttpGet(cookieUrl); final HttpResponse response = httpClient.execute(httpget); if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NO_CONTENT) { for (final Cookie cookie : httpClient.getCookieStore().getCookies()) { if (cookie.getName().equals(Parameters.acsid.getText())) { retObj = cookie; break; } } } else if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) { throw new NimbitsException("invalid token"); } else { throw new NimbitsException( "Error getting cookie: status code:" + response.getStatusLine().getStatusCode()); } httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } catch (UnsupportedEncodingException e) { throw new NimbitsException(e.getMessage()); } catch (ClientProtocolException e) { throw new NimbitsException(e.getMessage()); } catch (IOException e) { throw new NimbitsException(e.getMessage()); } return retObj; }
From source file:com.base.httpclient.HttpJsonClient.java
/** * get//w w w .ja v a 2 s . c o m * * @param url * URL * @param params * getkey-value * @return JSON * @throws ClientProtocolException * @throws IOException * @throws URISyntaxException */ public static String get(String url, Map<String, ?> params) throws ClientProtocolException, IOException, URISyntaxException { DefaultHttpClient httpclient = getHttpClient(); try { if (params != null && !(params.isEmpty())) { List<NameValuePair> values = new ArrayList<NameValuePair>(); for (Map.Entry<String, ?> entity : params.entrySet()) { BasicNameValuePair pare = new BasicNameValuePair(entity.getKey(), entity.getValue().toString()); values.add(pare); } String str = URLEncodedUtils.format(values, "UTF-8"); if (url.indexOf("?") > -1) { url += "&" + str; } else { url += "?" + str; } } URL pageURL = new URL(url); //pageUrl?httpget URI uri = new URI(pageURL.getProtocol(), pageURL.getHost(), pageURL.getPath(), pageURL.getQuery(), null); HttpGet httpget = createHttpUriRequest(HttpMethod.GET, uri); httpget.setHeader("Pragma", "no-cache"); httpget.setHeader("Cache-Control", "max-age=0, no-cache, no-store, must-revalidate"); httpget.setHeader("Connection", "keep-alive"); httpget.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); httpget.setHeader("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3"); httpget.setHeader("Accept-Charset", "gbk,utf-8;q=0.7,*;q=0.7"); httpget.setHeader("Referer", url); /*httpget.setHeader("Content-Encoding", "gzip"); httpget.setHeader("Accept-Encoding", "gzip, deflate");*/ //httpget.setHeader("Host", "s.taobao.com"); /*int temp = Integer.parseInt(Math.round(Math.random()*(MingSpiderService.UserAgent.length-1))+"");//??? httpget.setHeader("User-Agent", MingSpiderService.UserAgent[temp]);*/ HttpResponse response = httpclient.execute(httpget); httpclient.getCookieStore().clear(); int resStatu = response.getStatusLine().getStatusCode(); String html = ""; if (resStatu == HttpStatus.SC_OK) {//200 HttpEntity entity = response.getEntity(); if (entity != null) { html = EntityUtils.toString(entity, "GBK"); EntityUtils.consume(entity); } } return html; } finally { httpclient.getConnectionManager().shutdown(); } }