List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams
public synchronized final HttpParams getParams()
From source file:com.juick.android.JuickMessagesAdapter.java
public static String setupProxyForURL(Context context, String url, DefaultHttpClient httpClient) { if (useDirectImageMode(context)) { return url; }//from w ww . j a v a2s . c om String loadURl = url; if (imageLoadMode.contains("japroxy")) { final int HEIGHT = (int) (((Activity) context).getWindow().getWindowManager().getDefaultDisplay() .getHeight() * imageHeightPercent); final int WIDTH = (int) (((Activity) context).getWindow().getWindowManager().getDefaultDisplay() .getWidth()); String host = "ja.servebeer.com:8080"; //String host = "192.168.1.77:8080"; if (url.startsWith("https://i.juick.com")) { url = "http" + url.substring(5); } loadURl = "http://" + host + "/img?url=" + Uri.encode(url) + "&height=" + HEIGHT + "&width=" + WIDTH; } if (imageLoadMode.contains("weserv")) { final int HEIGHT = (int) (((Activity) context).getWindow().getWindowManager().getDefaultDisplay() .getHeight() * imageHeightPercent); // WESERV.NL if (url.startsWith("https://")) { loadURl = "http://images.weserv.nl/?url=ssl:" + Uri.encode(url.substring(8)) + "&h=" + HEIGHT + "&q=0.5"; } else if (url.startsWith("http://")) { loadURl = "http://images.weserv.nl/?url=" + Uri.encode(url.substring(7)) + "&h=" + HEIGHT + "&q=0.5"; } else { // keep url } } if (imageLoadMode.contains("fastun")) { if (httpClient != null) { SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); String proxyLogin = sp.getString("imageproxy.login", ""); String proxyPassword = sp.getString("imageproxy.password", ""); if (proxyLogin.length() > 0 && proxyPassword.length() > 0) { httpClient.getCredentialsProvider().setCredentials(new AuthScope("fastun.com", 7000), new UsernamePasswordCredentials(proxyLogin, proxyPassword)); HttpHost proxy = new HttpHost("fastun.com", 7000); httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } } } return loadURl; }
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
/** * Prepare login information for shibboleth environment. * * @param username//from w w w .j a va2 s. c om * @param thePassword * @param userChanged * @return True if the user should login as external user, false if * shibboleth is used. */ private boolean prepareShibbolethLogin(String username, char[] thePassword, boolean userChanged) { String idpURLString = ConfigurationEntry.SERVER_IDP_LAST_CONNECTED_ECP.getValue(getController()); if (StringUtils.isBlank(idpURLString)) { shibUsername = null; shibToken = null; throw new SecurityException("Your organization is unreachable"); } else if (userChanged) { shibUsername = null; shibToken = null; } else if ("ext".equals(idpURLString)) { return true; } boolean tokenIsValid = false; try { tokenIsValid = shibToken != null && shibToken.contains(":") && System.currentTimeMillis() <= Long .valueOf(shibToken.substring(shibToken.indexOf(':') + 1, shibToken.length())); } catch (Exception e) { logFine("Unusable Shibboleth Token: " + shibToken + " valid ? " + tokenIsValid); shibUsername = null; shibToken = null; } if (StringUtils.isBlank(shibUsername) || StringUtils.isBlank(shibToken) || !tokenIsValid) { String spURL = getWebURL( Constants.LOGIN_SHIBBOLETH_CLIENT_URI + '/' + getController().getMySelf().getId(), false); URI spURI; try { spURI = new URI(spURL); } catch (URISyntaxException e) { shibUsername = null; shibToken = null; // Should not happen throw new RuntimeException("Unable to resolve service provider URL: " + spURL + ". " + e); } URI idpURI = null; try { idpURI = new URI(idpURLString); } catch (Exception e) { shibUsername = null; shibToken = null; // Should not happen throw new RuntimeException("Unable to resolve identity provider URL: " + ConfigurationEntry.SERVER_IDP_LAST_CONNECTED_ECP.getValue(getController()) + ". " + e); } // PFC-2496: Start DefaultHttpClient dhc = new DefaultHttpClient(); // Set Proxy credentials, if configured if (ConfigurationEntry.HTTP_PROXY_HOST.hasValue(getController())) { String proxyUsername = ""; String proxyPassword = ""; if (ConfigurationEntry.HTTP_PROXY_USERNAME.hasValue(getController())) { proxyUsername = ConfigurationEntry.HTTP_PROXY_USERNAME.getValue(getController()); if (ConfigurationEntry.HTTP_PROXY_PASSWORD.hasValue(getController())) { proxyPassword = ConfigurationEntry.HTTP_PROXY_PASSWORD.getValue(getController()); } } dhc.getCredentialsProvider().setCredentials( new AuthScope(ConfigurationEntry.HTTP_PROXY_HOST.getValue(getController()), ConfigurationEntry.HTTP_PROXY_PORT.getValueInt(getController())), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); HttpHost proxy = new HttpHost(ConfigurationEntry.HTTP_PROXY_HOST.getValue(getController()), ConfigurationEntry.HTTP_PROXY_PORT.getValueInt(getController())); dhc.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // PFC-2496: End ECPAuthenticator auth = new ECPAuthenticator(dhc, username, new String(thePassword), idpURI, spURI); String[] result; try { result = auth.authenticate(); shibUsername = result[0]; shibToken = result[1]; } catch (ECPUnauthorizedException e) { shibbolethUnauthRetriesSkip = ConfigurationEntry.SERVER_LOGIN_SKIP_RETRY .getValueInt(getController()); shibUsername = null; shibToken = null; throw new SecurityException(e); } catch (ECPAuthenticationException e) { shibUsername = null; shibToken = null; throw new SecurityException(e); } } return false; }
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;/*from w ww . j a va 2 s . c om*/ 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:org.apache.manifoldcf.crawler.connectors.meridio.meridiowrapper.MeridioWrapper.java
/** The Meridio Wrapper constructor that calls the Meridio login method * *@param log a handle to a Log4j logger *@param meridioDmwsUrl the URL to the Meridio Document Management Web Service *@param meridioRmwsUrl the URL to the Meridio Records Management Web Service *@param dmwsProxyHost the proxy for DMWS, or null if none *@param dmwsProxyPort the proxy port for DMWS, or -1 if default *@param rmwsProxyHost the proxy for RMWS, or null if none *@param rmwsProxyPort the proxy port for RMWS, or -1 if default *@param userName the username of the user to log in as, must include the Windows, e.g. domain\\user *@param password the password of the user who is logging in *@param clientWorkstation an identifier for the client workstation, could be the IP address, for auditing purposes *@param protocolFactory the protocol factory object to use for https communication *@param engineConfigurationFile the engine configuration object to use to communicate with the web services * *@throws RemoteException if an error is encountered logging into Meridio *///from w ww . ja v a2 s. co m public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl, String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort, String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation, javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile) throws RemoteException, NumberFormatException { // Initialize local instance variables oLog = log; this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile); this.clientWorkstation = clientWorkstation; // Set up the pool. // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service // it connects with (because each one has a potentially different proxy setup), OR we can have a different // httpclient for each service. The latter approach is obviously the more efficient, so I've chosen to do it // that way. PoolingClientConnectionManager localConnectionManager = new PoolingClientConnectionManager(); localConnectionManager.setMaxTotal(1); if (mySSLFactory != null) { SSLSocketFactory myFactory = new SSLSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier()); Scheme myHttpsProtocol = new Scheme("https", 443, myFactory); localConnectionManager.getSchemeRegistry().register(myHttpsProtocol); } connectionManager = localConnectionManager; // Parse the user and password values int index = userName.indexOf("\\"); String domainUser; String domain; if (index != -1) { domainUser = userName.substring(index + 1); domain = userName.substring(0, index); if (oLog != null && oLog.isDebugEnabled()) oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'"); } else { domain = null; domainUser = userName; if (oLog != null && oLog.isDebugEnabled()) oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified"); } if (oLog != null && oLog.isDebugEnabled()) { if (password != null && password.length() > 0) oLog.debug("Meridio: Password exists"); else oLog.debug("Meridio: Password is null"); } // Initialize the three httpclient objects // dmws first BasicHttpParams dmwsParams = new BasicHttpParams(); dmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); dmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); dmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); dmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000); dmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); DefaultHttpClient localDmwsHttpClient = new DefaultHttpClient(connectionManager, dmwsParams); // No retries localDmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); localDmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy()); if (domainUser != null) { localDmwsHttpClient.getCredentialsProvider().setCredentials( new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize proxy if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) { int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(dmwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { localDmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(dmwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(dmwsProxyHost, port); localDmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } dmwsHttpClient = localDmwsHttpClient; // rmws BasicHttpParams rmwsParams = new BasicHttpParams(); rmwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); rmwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); rmwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); rmwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000); rmwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); DefaultHttpClient localRmwsHttpClient = new DefaultHttpClient(connectionManager, rmwsParams); // No retries localRmwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); localRmwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy()); if (domainUser != null) { localRmwsHttpClient.getCredentialsProvider().setCredentials( new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize proxy if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) { int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(rmwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { localRmwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(rmwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(rmwsProxyHost, port); localRmwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } rmwsHttpClient = localRmwsHttpClient; // mcws if (meridioManifoldCFWSUrl != null) { BasicHttpParams mcwsParams = new BasicHttpParams(); mcwsParams.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true); mcwsParams.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false); mcwsParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); mcwsParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 900000); mcwsParams.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true); DefaultHttpClient localMcwsHttpClient = new DefaultHttpClient(connectionManager, mcwsParams); // No retries localMcwsHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); localMcwsHttpClient.setRedirectStrategy(new DefaultRedirectStrategy()); if (domainUser != null) { localMcwsHttpClient.getCredentialsProvider().setCredentials( new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()), new NTCredentials(domainUser, password, currentHost, domain)); } // Initialize proxy if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) { int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080 : Integer.parseInt(mcwsProxyPort); // Configure proxy authentication if (domainUser != null && domainUser.length() > 0) { localMcwsHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mcwsProxyHost, port), new NTCredentials(domainUser, password, currentHost, domain)); } HttpHost proxy = new HttpHost(mcwsProxyHost, port); localMcwsHttpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } mcwsHttpClient = localMcwsHttpClient; } else mcwsHttpClient = null; // Set up the stub handles /*================================================================= * Get a handle to the DMWS *================================================================*/ MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration); MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator); meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName()); meridioDMWebService.setUsername(userName); meridioDMWebService.setPassword(password); meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient); meridioDMWebService_ = meridioDMWebService; /*================================================================= * Get a handle to the RMWS *================================================================*/ MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration); MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator); meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName()); meridioRMWebService.setUsername(userName); meridioRMWebService.setPassword(password); meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient); meridioRMWebService_ = meridioRMWebService; /*================================================================= * Get a handle to the MeridioMetaCarta Web Service *================================================================*/ if (meridioManifoldCFWSUrl != null) { MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration); Service McWsService = null; MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl, McWsService); meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName()); meridioMetaCartaWebService.setUsername(userName); meridioMetaCartaWebService.setPassword(password); meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient); meridioMCWS_ = meridioMetaCartaWebService; } this.loginUnified(); }
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);/*from w w w. j a va2 s .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); } } }
From source file:org.apache.stratos.cli.RestClient.java
/** * Handle http post request. Return String * * @param httpClient This should be httpClient which used to connect to rest endpoint * @param resourcePath This should be REST endpoint * @param jsonParamString The json string which should be executed from the post request * @return The HttpResponse//from w ww . j av a 2 s .com * @throws IOException if any errors occur when executing the request */ public HttpResponse doPost(DefaultHttpClient httpClient, String resourcePath, String jsonParamString) throws IOException { HttpPost postRequest = new HttpPost(resourcePath); StringEntity input = new StringEntity(jsonParamString); input.setContentType("application/json"); postRequest.setEntity(input); String userPass = username + ":" + password; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); postRequest.addHeader("Authorization", basicAuth); httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, TIME_OUT_PARAM); HttpConnectionParams.setSoTimeout(params, TIME_OUT_PARAM); HttpResponse response = httpClient.execute(postRequest); return response; }
From source file:org.apache.stratos.cli.RestClient.java
/** * Handle http get request. Return String * * @param httpClient This should be httpClient which used to connect to rest endpoint * @param resourcePath This should be REST endpoint * @return The HttpResponse/*from w w w. j av a 2 s . co m*/ * @throws org.apache.http.client.ClientProtocolException and IOException * if any errors occur when executing the request */ public HttpResponse doGet(DefaultHttpClient httpClient, String resourcePath) throws IOException { HttpGet getRequest = new HttpGet(resourcePath); getRequest.addHeader("Content-Type", "application/json"); String userPass = username + ":" + password; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); getRequest.addHeader("Authorization", basicAuth); httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, TIME_OUT_PARAM); HttpConnectionParams.setSoTimeout(params, TIME_OUT_PARAM); HttpResponse response = httpClient.execute(getRequest); return response; }
From source file:org.apache.stratos.cli.RestClient.java
public HttpResponse doDelete(DefaultHttpClient httpClient, String resourcePath) throws IOException { HttpDelete httpDelete = new HttpDelete(resourcePath); httpDelete.addHeader("Content-Type", "application/json"); String userPass = username + ":" + password; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); httpDelete.addHeader("Authorization", basicAuth); httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, TIME_OUT_PARAM); HttpConnectionParams.setSoTimeout(params, TIME_OUT_PARAM); HttpResponse response = httpClient.execute(httpDelete); return response; }
From source file:org.apache.stratos.cli.RestClient.java
public HttpResponse doPut(DefaultHttpClient httpClient, String resourcePath, String jsonParamString) throws IOException { HttpPut httpPutRequest = new HttpPut(resourcePath); StringEntity input = new StringEntity(jsonParamString); input.setContentType("application/json"); httpPutRequest.setEntity(input);/*from w w w .jav a 2s. c om*/ String userPass = username + ":" + password; String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userPass.getBytes("UTF-8")); httpPutRequest.addHeader("Authorization", basicAuth); httpClient = (DefaultHttpClient) WebClientWrapper.wrapClient(httpClient); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, TIME_OUT_PARAM); HttpConnectionParams.setSoTimeout(params, TIME_OUT_PARAM); HttpResponse response = httpClient.execute(httpPutRequest); return response; }