List of usage examples for org.apache.http.impl.client DefaultHttpClient getCookieStore
public synchronized final CookieStore getCookieStore()
From source file:com.farmafene.commons.cas.LoginTGT.java
/** * @param lt/*from w w w .j a va 2 s .c om*/ * @param user * @param password * @return */ private Cookie doLoginCookie(LoginTicketContainer lt, String user, String password) { Cookie doLoginCookie = null; HttpResponse res = null; HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(getCasServerURL()); DefaultHttpClient client = null; client = f.getClient(); HttpContext localContext = new BasicHttpContext(); BasicCookieStore cs = new BasicCookieStore(); cs.addCookie(lt.getSessionCookie()); HttpPost post = new HttpPost(getURL("login")); client.setCookieStore(cs); localContext.setAttribute(ClientContext.COOKIE_STORE, cs); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("lt", lt.getLoginTicket())); nameValuePairs.add(new BasicNameValuePair("execution", lt.getExecution())); nameValuePairs.add(new BasicNameValuePair("_eventId", "submit")); nameValuePairs.add(new BasicNameValuePair("username", user)); nameValuePairs.add(new BasicNameValuePair("password", password)); try { post.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } catch (UnsupportedEncodingException e) { AuriusAuthException ex = new AuriusAuthException("UnsupportedEncodingException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } try { res = client.execute(post, localContext); if (res.getStatusLine().getStatusCode() != 200) { AuriusAuthException ex = new AuriusAuthException("Error"); logger.error("Excepcion en el login", ex); throw ex; } } catch (ClientProtocolException e) { AuriusAuthException ex = new AuriusAuthException("ClientProtocolException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } if (client.getCookieStore().getCookies() != null) { for (Cookie c : client.getCookieStore().getCookies()) { if (getCasTGCName().equals(c.getName())) { doLoginCookie = c; break; } } } if (doLoginCookie == null) { throw new AuriusAuthException("No se ha logrado el login"); } if (logger.isDebugEnabled()) { logger.debug("Obtenido: " + doLoginCookie); } return doLoginCookie; }
From source file:de.nware.app.hsDroid.logic.LoginThread.java
License:asdf
/** * Login fr Online Service2.// www. j a va 2 s . co m * * @throws Exception */ private void doLogin() throws Exception { DefaultHttpClient client = new DefaultHttpClient(); HttpResponse response; HttpEntity entity; // progressHandle.sendMessage(progressHandle.obtainMessage(1)); Message connectMessage = mParentHandler.obtainMessage(); connectMessage.what = MESSAGE_PROGRESS_CONNECT; mParentHandler.sendMessage(connectMessage); // Post Daten zusammen bauen HttpPost post = new HttpPost(UPDATE_URL); List<NameValuePair> postData = new ArrayList<NameValuePair>(); postData.add(new BasicNameValuePair("asdf", this.username)); postData.add(new BasicNameValuePair("fdsa", this.password)); postData.add(new BasicNameValuePair("submit", "Anmelden")); // header bauen post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(postData, HTTP.UTF_8)); // http Anfrage starten response = client.execute(post); Message parseMessage = mParentHandler.obtainMessage(); parseMessage.what = MESSAGE_PROGRESS_PARSE; // Send Message to mainThread mParentHandler.sendMessage(parseMessage); entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader rd = new BufferedReader(new InputStreamReader(is), 4096); String line; int count = 0; // response auswerten while ((line = rd.readLine()) != null) { // mglichkeit den thread hier zu stoppen... sinnvoll? if (mStoppingThread) { break; } // TODO check login success loginStringTest(line, count); // session id holen if (line.contains("asi=")) { // wenn eine session id gefunden wird, kann man davon // ausgehen, dass man angemeldet is ;) int begin = line.indexOf("asi=") + 4; StaticSessionData.asiKey = line.substring(begin, begin + 20); break; } count++; } rd.close(); is.close(); Message cookieMessage = mParentHandler.obtainMessage(); cookieMessage.what = MESSAGE_PROGRESS_COOKIE; mParentHandler.sendMessage(cookieMessage); if (client.getCookieStore().getCookies().size() != 0) { // Speichere Login zeit StaticSessionData.cookieMillis = System.currentTimeMillis(); StaticSessionData.cookies = client.getCookieStore().getCookies(); // for (int i = 0; i < StaticSessionData.cookies.size(); i++) { // if (StaticSessionData.cookies.get(i) == null) { // Log.e("login", "cookie:" + i + "empty"); // } // // Log.d("login: " + i + " domain", "" + // StaticSessionData.cookies.get(i).getDomain()); // Log.d("login: " + i + " name", "" + // StaticSessionData.cookies.get(i).getName()); // Log.d("login: " + i + " path", "" + // StaticSessionData.cookies.get(i).getPath()); // Log.d("login: " + i + " value", "" + // StaticSessionData.cookies.get(i).getValue()); // Log.d("login: " + i + " version", "" + // StaticSessionData.cookies.get(i).getVersion()); // Log.d("login: " + i + " secure", "" + // (StaticSessionData.cookies.get(i).isSecure() ? "yes" : "no")); // Log.d("login: " + i + " expired", "" // + (StaticSessionData.cookies.get(i).isExpired(new Date()) ? "yes" // : "no")); // Log.d("login: " + i + " persistent", "" // + (StaticSessionData.cookies.get(i).isPersistent() ? "yes" : // "no")); // Log.d("login: " + i + " expire Date", "" + // StaticSessionData.cookies.get(i).getExpiryDate()); // // } // cookies darf nicht leer sein } else { throw new HSLoginException(ERROR_MSG_COOKIE_MISSING); } if (entity != null) entity.consumeContent(); mThreadStatus = STATE_DONE; Message oMessage = mParentHandler.obtainMessage(); oMessage.what = MESSAGE_COMPLETE; mParentHandler.sendMessage(oMessage); }
From source file:com.farmafene.commons.cas.LoginTGT.java
/** * @return/*from w w w . j av a 2 s . co m*/ */ private LoginTicketContainer processInitRequest() { LoginTicketContainer processInitRequest = null; HttpResponse res = null; HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(getCasServerURL()); DefaultHttpClient client = null; client = f.getClient(); HttpContext localContext = new BasicHttpContext(); BasicCookieStore cs = new BasicCookieStore(); HttpPost post = new HttpPost(getURL("login")); client.setCookieStore(cs); localContext.setAttribute(ClientContext.COOKIE_STORE, cs); try { res = client.execute(post, localContext); } catch (ClientProtocolException e) { AuriusAuthException ex = new AuriusAuthException("ClientProtocolException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } InputStream is = null; try { is = res.getEntity().getContent(); } catch (IllegalStateException e) { AuriusAuthException ex = new AuriusAuthException("IllegalStateException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } byte[] buffer = new byte[1024]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); int leido = 0; try { while ((leido = is.read(buffer)) > 0) { baos.write(buffer, 0, leido); } } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } String html = baos.toString().replace("\n", "").replace("\r", ""); /* * Buscamos los tipos de "input" */ String[] inputs = html.split("<\\s*input\\s+"); processInitRequest = new LoginTicketContainer(); for (String input : inputs) { String value = null; if (null != (value = search(input, "lt"))) { processInitRequest.setLoginTicket(value); } else if (null != (value = search(input, "execution"))) { processInitRequest.setExecution(value); } } /* * Obtenemos la session Cookie */ if (client.getCookieStore().getCookies() != null) { for (Cookie c : client.getCookieStore().getCookies()) { if (getJSessionCookieName().equals(c.getName())) { processInitRequest.setSessionCookie(c); } } } if (null != baos) { try { baos.close(); } catch (IOException e) { logger.error("Error al cerrar el OutputStream", e); } } if (null != is) { try { is.close(); } catch (IOException e) { logger.error("Error al cerrar el InputStream", e); } } if (logger.isDebugEnabled()) { logger.debug("Obtenido: " + processInitRequest); } return processInitRequest; }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String[] getToken() throws JSONParserStatusCodeException { String url = "gui/token.html"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }//from w ww.j av a2 s .c o m String tokenString = null; String cookieString = "NULL"; HttpResponse httpResponse; DefaultHttpClient httpclient; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "youTorrent Controller"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(hostname, port, protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpGet httpget = new HttpGet(url); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); // Log.d("Debug", "Token - mStatusCode: " + mStatusCode); if (mStatusCode != 200) { httpclient.getConnectionManager().shutdown(); throw new JSONParserStatusCodeException(mStatusCode); } if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } // Log.d("Debug", "JSONParser - cookieString: " + cookieString); // Get token is = entity.getContent(); // Build response BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); tokenString = sb.toString(); // Replace html tags with "" tokenString = tokenString.replaceAll("<.*?>", "").trim(); // Log.d("Debug", "API - Token: " + tokenString); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.i("Debug", "Exception " + e.toString()); } return new String[] { tokenString, cookieString }; }
From source file:com.googlecode.noweco.webmail.portal.bull.BullWebmailPortalConnector.java
public PortalConnection connect(final HttpHost proxy, final String user, final String password) throws IOException { DefaultHttpClient httpclient = UnsecureHttpClientFactory.INSTANCE.createUnsecureHttpClient(proxy); HttpPost httpost;// w ww .j a v a2 s. c o m List<NameValuePair> nvps; HttpResponse rsp; int statusCode; HttpEntity entity; // mailbox does not appear with no FR language // with Mozilla actions are simple new ClientParamBean(httpclient.getParams()).setDefaultHeaders(Arrays.asList( (Header) new BasicHeader("Accept-Language", "fr-fr,fr;q=0.8,en;q=0.5,en-us;q=0.3"), new BasicHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1"))); String firstEntity = authent(httpclient, user, password); Matcher datasMatcher = DATAS.matcher(firstEntity); if (!datasMatcher.find()) { Matcher matcher = NEW_PASSWD.matcher(firstEntity); if (matcher.find()) { // try a bad password authent(httpclient, user, password + "BAD"); // and retry good password (expired) firstEntity = authent(httpclient, user, password); datasMatcher = DATAS.matcher(firstEntity); if (!datasMatcher.find()) { throw new IOException("Unable to find Datas, after bad password try"); } } else { throw new IOException("Unable to find Datas"); } } // STEP 2 : WEB-MAIL httpost = new HttpPost("https://bullsentry.bull.fr:443/cgi/wway_cookie"); nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("TdsName", "PILX")); nvps.add(new BasicNameValuePair("Proto", "s")); nvps.add(new BasicNameValuePair("Port", "443")); nvps.add(new BasicNameValuePair("Cgi", "cgi")); nvps.add(new BasicNameValuePair("Mode", "set")); nvps.add(new BasicNameValuePair("Total", "3")); nvps.add(new BasicNameValuePair("Current", "1")); nvps.add(new BasicNameValuePair("ProtoR", "s")); nvps.add(new BasicNameValuePair("PortR", "443")); 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("Datas", datasMatcher.group(1))); Matcher lastCnxMatcher = LAST_CNX.matcher(firstEntity); if (!lastCnxMatcher.find()) { throw new IOException("Unable to find lastCnx"); } nvps.add(new BasicNameValuePair("lastCnx", lastCnxMatcher.group(1))); httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); // send the request rsp = httpclient.execute(httpost); statusCode = rsp.getStatusLine().getStatusCode(); if (statusCode != 200) { throw new IOException("Unable to connect to bull portail, status code : " + statusCode); } if (LOGGER.isTraceEnabled()) { LOGGER.debug("STEP 2 Apps Cookie : {}", httpclient.getCookieStore().getCookies()); } // free result resources entity = rsp.getEntity(); if (entity != null) { if (LOGGER.isTraceEnabled()) { LOGGER.trace("STEP 2 Entity : {}", EntityUtils.toString(entity)); } EntityUtils.consume(entity); } // STEP 3 : telemail HttpGet httpGet = new HttpGet("https://telemail.bull.fr:443/HomePage.nsf"); rsp = httpclient.execute(httpGet); entity = rsp.getEntity(); String secondEntity = EntityUtils.toString(entity); if (entity != null) { LOGGER.trace("STEP 3 Entity : {}", secondEntity); EntityUtils.consume(entity); } Matcher nsfMatcher = PATTERN.matcher(secondEntity); if (!nsfMatcher.find()) { throw new IOException("Unable to find nsf"); } String pathPrefix = nsfMatcher.group(3).replace('\\', '/'); LOGGER.debug("pathPrefix : {}", pathPrefix); String protocol = nsfMatcher.group(1); int port; if ("http".equals(protocol)) { port = 80; } else if ("https".equals(protocol)) { port = 443; } else { throw new IOException("Unknown protocol " + protocol); } return new DefaultPortalConnection(httpclient, new HttpHost(nsfMatcher.group(2), port, protocol), pathPrefix); }
From source file:com.lgallardo.youtorrentcontroller.JSONParser.java
public String getNewCookie() throws JSONParserStatusCodeException { String url = "login"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }/*w ww .j a va 2 s .com*/ String cookieString = null; HttpResponse httpResponse; DefaultHttpClient httpclient; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(hostname, port, protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); // Set http parameters httpclient.setParams(httpParameters); try { // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); // // In order to pass the username and password we must set the pair name value List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", this.username)); nvps.add(new BasicNameValuePair("password", this.password)); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.e("Debug", "Exception " + e.toString()); } if (cookieString == null) { cookieString = ""; } return cookieString; }
From source file:com.lgallardo.qbittorrentclient.JSONParser.java
public String getNewCookie() throws JSONParserStatusCodeException { String url = "login"; // if server is publish in a subfolder, fix url if (subfolder != null && !subfolder.equals("")) { url = subfolder + "/" + url; }// w w w .j a v a 2s . c o m String cookieString = null; HttpResponse httpResponse; DefaultHttpClient httpclient; HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = connection_timeout * 1000; // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = data_timeout * 1000; // Set http parameters HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); HttpProtocolParams.setUserAgent(httpParameters, "qBittorrent for Android"); HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); // Making HTTP request HttpHost targetHost = new HttpHost(hostname, port, protocol); // httpclient = new DefaultHttpClient(); httpclient = getNewHttpClient(); httpclient.setParams(httpParameters); try { // AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // // UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(this.username, this.password); // // httpclient.getCredentialsProvider().setCredentials(authScope, credentials); url = protocol + "://" + hostname + ":" + port + "/" + url; HttpPost httpget = new HttpPost(url); // // In order to pass the username and password we must set the pair name value List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("username", this.username)); nvps.add(new BasicNameValuePair("password", this.password)); httpget.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse response = httpclient.execute(targetHost, httpget); HttpEntity entity = response.getEntity(); StatusLine statusLine = response.getStatusLine(); int mStatusCode = statusLine.getStatusCode(); if (mStatusCode == 200) { // Save cookie List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue() + "; domain=" + cookies.get(0).getDomain(); cookieString = cookies.get(0).getName() + "=" + cookies.get(0).getValue(); } } if (entity != null) { entity.consumeContent(); } // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } catch (Exception e) { Log.e("Debug", "Exception " + e.toString()); } if (cookieString == null) { cookieString = ""; } return cookieString; }
From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java
public boolean login() { // System.out.println("--L--- LOGIN START -----"); String login_url = "https://www.geocaching.com/login/default.aspx"; DefaultHttpClient client2 = null; HttpHost proxy = null;// w w w .j a v a2s.c o m if (CacheDownloader.DEBUG2_) { // NEVER enable this on a production release!!!!!!!!!! // NEVER enable this on a production release!!!!!!!!!! trust_Every_ssl_cert(); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); HttpParams params = new BasicHttpParams(); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); proxy = new HttpHost("192.168.0.1", 8888); params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry); client2 = new DefaultHttpClient(cm, params); // NEVER enable this on a production release!!!!!!!!!! // NEVER enable this on a production release!!!!!!!!!! } else { HttpParams httpParameters = new BasicHttpParams(); int timeoutConnection = 10000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); int timeoutSocket = 10000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); client2 = new DefaultHttpClient(httpParameters); } if (CacheDownloader.DEBUG2_) { client2.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // read first page to check for login // read first page to check for login // read first page to check for login String websiteData2 = null; URI uri2 = null; try { uri2 = new URI(login_url); } catch (URISyntaxException e) { e.printStackTrace(); return false; } client2.setCookieStore(cookie_jar); HttpGet method2 = new HttpGet(uri2); method2.addHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.10) Gecko/20071115 Firefox/2.0.0.10"); method2.addHeader("Pragma", "no-cache"); method2.addHeader("Accept-Language", "en"); HttpResponse res = null; try { res = client2.execute(method2); } catch (ClientProtocolException e1) { e1.printStackTrace(); return false; } catch (IOException e1) { e1.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } InputStream data = null; try { data = res.getEntity().getContent(); } catch (IllegalStateException e1) { e1.printStackTrace(); return false; } catch (IOException e1) { e1.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } websiteData2 = generateString(data); if (CacheDownloader.DEBUG_) System.out.println("111 cookies=" + dumpCookieStore(client2.getCookieStore())); cookie_jar = client2.getCookieStore(); // on every page final Matcher matcherLogged2In = patternLogged2In.matcher(websiteData2); if (matcherLogged2In.find()) { if (CacheDownloader.DEBUG_) System.out.println("login: -> already logged in (1)"); return true; } // after login final Matcher matcherLoggedIn = patternLoggedIn.matcher(websiteData2); if (matcherLoggedIn.find()) { if (CacheDownloader.DEBUG_) System.out.println("login: -> already logged in (2)"); return true; } // read first page to check for login // read first page to check for login // read first page to check for login // ok post login data as formdata // ok post login data as formdata // ok post login data as formdata // ok post login data as formdata HttpPost method = new HttpPost(uri2); method.addHeader("User-Agent", "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.0) Firefox/7.0"); method.addHeader("Pragma", "no-cache"); method.addHeader("Content-Type", "application/x-www-form-urlencoded"); method.addHeader("Accept-Language", "en"); List<NameValuePair> loginInfo = new ArrayList<NameValuePair>(); loginInfo.add(new BasicNameValuePair("__EVENTTARGET", "")); loginInfo.add(new BasicNameValuePair("__EVENTARGUMENT", "")); String[] viewstates = getViewstates(websiteData2); if (CacheDownloader.DEBUG_) System.out.println("vs==" + viewstates[0]); putViewstates(loginInfo, viewstates); loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$tbUsername", this.main_aagtl.global_settings.options_username)); loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$tbPassword", this.main_aagtl.global_settings.options_password)); loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$btnSignIn", "Login")); loginInfo.add(new BasicNameValuePair("ctl00$ContentBody$cbRememberMe", "on")); //for (int i = 0; i < loginInfo.size(); i++) //{ // System.out.println("x*X " + loginInfo.get(i).getName() + " " + loginInfo.get(i).getValue()); //} // set cookies client2.setCookieStore(cookie_jar); HttpEntity entity = null; try { entity = new UrlEncodedFormEntity(loginInfo, HTTP.UTF_8); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return false; } // try // { // System.out.println("1 " + entity.toString()); // InputStream in2 = entity.getContent(); // InputStreamReader ir2 = new InputStreamReader(in2, "utf-8"); // BufferedReader r = new BufferedReader(ir2); // System.out.println("line=" + r.readLine()); // } // catch (Exception e2) // { // e2.printStackTrace(); // } method.setEntity(entity); HttpResponse res2 = null; try { res2 = client2.execute(method); if (CacheDownloader.DEBUG_) System.out.println("login response ->" + String.valueOf(res2.getStatusLine())); } catch (ClientProtocolException e) { e.printStackTrace(); return false; } catch (IOException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } // for (int x = 0; x < res2.getAllHeaders().length; x++) // { // System.out.println("## n=" + res2.getAllHeaders()[x].getName()); // System.out.println("## v=" + res2.getAllHeaders()[x].getValue()); // } InputStream data2 = null; try { data2 = res2.getEntity().getContent(); } catch (IllegalStateException e1) { e1.printStackTrace(); return false; } catch (IOException e1) { e1.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } websiteData2 = generateString(data2); if (CacheDownloader.DEBUG_) System.out.println("2222 cookies=" + dumpCookieStore(client2.getCookieStore())); cookie_jar = client2.getCookieStore(); String[] viewstates2 = getViewstates(websiteData2); if (CacheDownloader.DEBUG_) System.out.println("vs==" + viewstates2[0]); // System.out.println("******"); // System.out.println("******"); // System.out.println("******"); // System.out.println(websiteData2); // System.out.println("******"); // System.out.println("******"); // System.out.println("******"); return true; }
From source file:de.betterform.connector.http.AbstractHTTPConnector.java
protected void execute(HttpRequestBase httpRequestBase) throws Exception { // (new HttpClient()).executeMethod(httpMethod); //HttpClient client = new HttpClient(); HttpParams httpParams = new BasicHttpParams(); DefaultHttpClient client = ConnectorFactory.getFactory().getHttpClient(httpParams); if (!getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("SSL_CUSTOM_SCHEME"); LOGGER.debug("SSL_CUSTOM_SCHEME: Factory: " + Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT)); String contextPath = Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT); if (contextPath != null) { initSSLScheme(contextPath);/* ww w . ja va 2s . com*/ } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("context params>>>"); Map map = getContext(); Iterator keys = map.keySet().iterator(); while (keys.hasNext()) { String key = keys.next().toString(); Object value = map.get(key); if (value != null) LOGGER.debug(key + "=" + value.toString()); } LOGGER.debug("<<<end params"); } String username = null; String password = null; String realm = null; //add custom header to signal XFormsFilter to not process this internal request //httpMethod.setRequestHeader(BetterFORMConstants.BETTERFORM_INTERNAL,"true"); httpRequestBase.addHeader(BetterFORMConstants.BETTERFORM_INTERNAL, "true"); /// *** copy all keys in map HTTP_REQUEST_HEADERS as http-submissionHeaders if (getContext().containsKey(HTTP_REQUEST_HEADERS)) { RequestHeaders httpRequestHeaders = (RequestHeaders) getContext().get(HTTP_REQUEST_HEADERS); // Iterator it = Map headersToAdd = new HashMap(); for (RequestHeader header : httpRequestHeaders.getAllHeaders()) { String headername = header.getName(); String headervalue = header.getValue(); if (headername.equals("username")) { username = headervalue; } else if (headername.equals("password")) { password = headervalue; } else if (headername.equals("realm")) { realm = headervalue; } else { if (headersToAdd.containsKey(headername)) { String formerValue = (String) headersToAdd.get(headername); headersToAdd.put(headername, formerValue + "," + headervalue); } else { if (headername.equals("accept-encoding")) { // do nothing LOGGER.debug("do not add accept-encoding:" + headervalue + " for request"); } else { headersToAdd.put(headername, headervalue); if (LOGGER.isDebugEnabled()) { LOGGER.debug("setting header: " + headername + " value: " + headervalue); } } } } } Iterator keyIterator = headersToAdd.keySet().iterator(); while (keyIterator.hasNext()) { String key = (String) keyIterator.next(); //httpMethod.setRequestHeader(new Header(key,(String) headersToAdd.get(key))); httpRequestBase.setHeader(key, (String) headersToAdd.get(key)); //httpRequestBase.addHeader(key, (String) headersToAdd.get(key)); } } if (httpRequestBase.containsHeader("Content-Length")) { //remove content-length if present httpclient will recalucalte the value. httpRequestBase.removeHeaders("Content-Length"); } if (username != null && password != null) { URI targetURI = null; //targetURI = httpMethod.getURI(); targetURI = httpRequestBase.getURI(); //client.getParams().setAuthenticationPreemptive(true); Credentials defaultcreds = new UsernamePasswordCredentials(username, password); if (realm == null) { realm = AuthScope.ANY_REALM; } //client.getState().setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); client.getCredentialsProvider() .setCredentials(new AuthScope(targetURI.getHost(), targetURI.getPort(), realm), defaultcreds); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(new HttpHost(targetURI.getHost()), basicAuth); BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache); //Needed? httpMethod.setDoAuthentication(true); } //alternative method for non-tomcat servers if (getContext().containsKey(REQUEST_COOKIE)) { //HttpState state = client.getState(); HttpParams state = client.getParams(); //state.setCookiePolicy(CookiePolicy.COMPATIBILITY); state.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); if (getContext().get(REQUEST_COOKIE) instanceof Cookie[]) { Cookie[] cookiesIn = (Cookie[]) getContext().get(REQUEST_COOKIE); if (cookiesIn[0] != null) { for (int i = 0; i < cookiesIn.length; i++) { Cookie cookie = cookiesIn[i]; //state.addCookie(cookie); client.getCookieStore().addCookie(cookie); } /* Cookie[] cookies = state.getCookies(); Header cookieOut = new CookieSpecBase().formatCookieHeader(cookies); httpMethod.setRequestHeader(cookieOut); client.setState(state); */ List<Cookie> cookies = client.getCookieStore().getCookies(); List<Header> cookieHeaders = new BrowserCompatSpec().formatCookies(cookies); Header[] headers = cookieHeaders.toArray(new Header[0]); for (int i = 0; i < headers.length; i++) { httpRequestBase.addHeader(headers[i]); } client.setParams(state); } } else { throw new MalformedCookieException( "Cookies must be passed as org.apache.commons.httpclient.Cookie objects."); } } if (getContext().containsKey(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) { LOGGER.debug("Using customSSL-Protocol-Handler"); Iterator<Scheme> schemes = ((Vector<Scheme>) getContext().get(AbstractHTTPConnector.SSL_CUSTOM_SCHEME)) .iterator(); while (schemes.hasNext()) { client.getConnectionManager().getSchemeRegistry().register(schemes.next()); } } if (httpRequestBase.getURI().isAbsolute()) { httpRequestBase.setHeader("host", httpRequestBase.getURI().getHost()); } HttpResponse httpResponse = client.execute(httpRequestBase); statusCode = httpResponse.getStatusLine().getStatusCode(); reasonPhrase = httpResponse.getStatusLine().getReasonPhrase(); try { if (statusCode >= 300) { // Allow 302 only if (statusCode != 302) { throw new XFormsInternalSubmitException(statusCode, reasonPhrase, EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } } this.handleHttpMethod(httpResponse); } catch (Exception e) { LOGGER.trace("AbstractHTTPConnector Exception: ", e); try { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), EntityUtils.toString(httpResponse.getEntity()), XFormsConstants.RESOURCE_ERROR); } catch (IOException e1) { throw new XFormsInternalSubmitException(httpResponse.getStatusLine().getStatusCode(), httpResponse.getStatusLine().getReasonPhrase(), XFormsConstants.RESOURCE_ERROR); } } }