List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:sand.actionhandler.weibo.UdaClient.java
public static String syn(String url) { String content = ""; DefaultHttpClient httpclient = new DefaultHttpClient(); try {/* w w w .ja v a 2s .c o m*/ httpclient = createHttpClient(); HttpGet httpget = new HttpGet(url); // Execute HTTP request //System.out.println("executing request " + httpget.getURI()); //logger.info("executing request " + httpget.getURI()); // System.out.println("----------------------------------------"); // System.out.println(response.getStatusLine()); // System.out.println(response.getLastHeader("Content-Encoding")); // System.out.println(response.getLastHeader("Content-Length")); // System.out.println("----------------------------------------"); //System.out.println(entity.getContentType()); httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2965); httpget.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); CookieStore cookieStore = new BasicCookieStore(); addCookie(cookieStore); // httpclient.setCookieStore(cookieStore); //httpclient.ex HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { content = EntityUtils.toString(entity); System.out.println(content); System.out.println("----------------------------------------"); System.out.println("Uncompressed size: " + content.length()); } } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpclient.getConnectionManager().shutdown(); } return content; }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
public boolean isAPIAvailable(API api, APIStore store) throws APIManagementException { boolean available = false; if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) { String msg = "External APIStore endpoint URL or credentials are not defined. " + "Cannot proceed with checking API availability from the APIStore - " + store.getDisplayName(); throw new APIManagementException(msg); } else {/* w ww . ja va2 s. c o m*/ CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); boolean authenticated = authenticateAPIM(store, httpContext); if (authenticated) { available = isAPIAvailableInWSO2Store(api, store.getUsername(), store.getEndpoint(), httpContext); logoutFromExternalStore(store, httpContext); } return available; } }
From source file:org.alfresco.dataprep.UserService.java
/** * Login in alfresco share/*from ww w .j ava2s .c om*/ * * @param userName login user name * @param userPass login user password * @return true for successful user login */ public HttpState login(final String userName, final String userPass) { if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(userPass)) { throw new IllegalArgumentException("Parameter missing"); } AlfrescoHttpClient client = alfrescoHttpClientFactory.getObject(); HttpState state = null; org.apache.commons.httpclient.HttpClient theClient = new org.apache.commons.httpclient.HttpClient(); String reqURL = client.getShareUrl() + "share/page/dologin"; org.apache.commons.httpclient.methods.PostMethod post = new org.apache.commons.httpclient.methods.PostMethod( reqURL); NameValuePair[] formParams; CookieStore cookieStore = new BasicCookieStore(); HttpClientContext localContext = HttpClientContext.create(); localContext.setCookieStore(cookieStore); formParams = (new NameValuePair[] { new NameValuePair("username", userName), new NameValuePair("password", userPass), new NameValuePair("success", "/share/page/user/" + userName + "/dashboard"), new NameValuePair("failure", "/share/page/type/login?error=true") }); post.setRequestBody(formParams); try { int postStatus = theClient.executeMethod(post); if (302 == postStatus) { state = theClient.getState(); post.releaseConnection(); org.apache.commons.httpclient.methods.GetMethod get = new org.apache.commons.httpclient.methods.GetMethod( client.getShareUrl() + "share/page/user/" + userName + "/dashboard"); theClient.setState(state); theClient.executeMethod(get); get.releaseConnection(); } } catch (IOException e) { throw new RuntimeException("Failed to execute the request"); } return state; }
From source file:nl.armatiek.xslweb.configuration.WebApp.java
public CloseableHttpClient getHttpClient() { if (httpClient == null) { PoolingHttpClientConnectionManager cm; if (Context.getInstance().getTrustAllCerts()) { try { SSLContextBuilder scb = SSLContexts.custom(); scb.loadTrustMaterial(null, new TrustStrategy() { @Override/*w w w. ja v a2 s . c o m*/ public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = scb.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf) .register("http", new PlainConnectionSocketFactory()).build(); cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (Exception e) { logger.warn("Could not set HttpClient to trust all SSL certificates", e); cm = new PoolingHttpClientConnectionManager(); } } else { cm = new PoolingHttpClientConnectionManager(); } cm.setMaxTotal(200); cm.setDefaultMaxPerRoute(20); HttpHost localhost = new HttpHost("localhost", 80); cm.setMaxPerRoute(new HttpRoute(localhost), 50); HttpClientBuilder builder = HttpClients.custom().setConnectionManager(cm); builder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())); builder.setDefaultCookieStore(new BasicCookieStore()); httpClient = builder.build(); } return httpClient; }
From source file:com.redhat.red.offliner.Main.java
/** * Sets up components needed for the download process, including the {@link ExecutorCompletionService}, * {@link java.util.concurrent.Executor}, {@link org.apache.http.client.HttpClient}, and {@link ArtifactListReader} * instances. If baseUrls were provided on the command line, it will initialize the "global" baseUrls list to that. * Otherwise it will use {@link Options#DEFAULT_REPO_URL} and {@link Options#CENTRAL_REPO_URL} as the default * baseUrls. If specified, configures the HTTP proxy and username/password for authentication. * @throws MalformedURLException In case an invalid {@link URL} is given as a baseUrl. *//*from w ww. ja va 2 s. c om*/ protected void init() throws MalformedURLException { int threads = opts.getThreads(); executorService = Executors.newFixedThreadPool(threads, (final Runnable r) -> { // executorService = Executors.newCachedThreadPool( ( final Runnable r ) -> { final Thread t = new Thread(r); t.setDaemon(true); return t; }); executor = new ExecutorCompletionService<>(executorService); errors = new ConcurrentHashMap<String, Throwable>(); final PoolingHttpClientConnectionManager ccm = new PoolingHttpClientConnectionManager(); ccm.setMaxTotal(opts.getConnections()); final HttpClientBuilder builder = HttpClients.custom().setConnectionManager(ccm); final String proxy = opts.getProxy(); String proxyHost = proxy; int proxyPort = 8080; if (proxy != null) { final int portSep = proxy.lastIndexOf(':'); if (portSep > -1) { proxyHost = proxy.substring(0, portSep); proxyPort = Integer.parseInt(proxy.substring(portSep + 1)); } final HttpRoutePlanner planner = new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort)); builder.setRoutePlanner(planner); } client = builder.build(); final CredentialsProvider creds = new BasicCredentialsProvider(); cookieStore = new BasicCookieStore(); baseUrls = opts.getBaseUrls(); if (baseUrls == null) { baseUrls = new ArrayList<>(); } List<String> repoUrls = (baseUrls.isEmpty() ? DEFAULT_URLS : baseUrls); System.out.println("Planning download from:\n " + StringUtils.join(repoUrls, "\n ")); for (String repoUrl : repoUrls) { if (repoUrl != null) { final String user = opts.getUser(); if (user != null) { final URL u = new URL(repoUrl); final AuthScope as = new AuthScope(u.getHost(), UrlUtils.getPort(u)); creds.setCredentials(as, new UsernamePasswordCredentials(user, opts.getPassword())); } } if (proxy != null) { final String proxyUser = opts.getProxyUser(); if (proxyUser != null) { creds.setCredentials(new AuthScope(proxyHost, proxyPort), new UsernamePasswordCredentials(proxyUser, opts.getProxyPassword())); } } } artifactListReaders = new ArrayList<>(3); artifactListReaders.add(new FoloReportArtifactListReader()); artifactListReaders.add(new PlaintextArtifactListReader()); artifactListReaders.add(new PomArtifactListReader(opts.getSettingsXml(), opts.getTypeMapping(), creds)); }
From source file:org.wso2.carbon.apimgt.impl.publishers.WSO2APIPublisher.java
@Override public boolean createVersionedAPIToStore(API api, APIStore store, String version) throws APIManagementException { boolean published = false; if (store.getEndpoint() == null || store.getUsername() == null || store.getPassword() == null) { String msg = "External APIStore endpoint URL or credentials are not defined. Cannot proceed with " + "publishing API to the APIStore - " + store.getDisplayName(); throw new APIManagementException(msg); } else {/*from w ww . jav a 2 s . c o m*/ CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); boolean authenticated = authenticateAPIM(store, httpContext); if (authenticated) { //First try to login to store boolean added = addVersionedAPIToStore(api, store.getEndpoint(), version, httpContext, store.getDisplayName(), store.getUsername()); if (added) { //If API creation success,then try publishing the API published = publishAPIToStore(api.getId(), store.getEndpoint(), store.getUsername(), httpContext, store.getDisplayName()); } logoutFromExternalStore(store, httpContext); } } return published; }
From source file:org.bonitasoft.connectors.rest.RESTConnector.java
/** * Set the cookies to the builder based on the request cookies * //from www. j a va 2 s . co m * @param requestConfigurationBuilder The request builder * @param httpClientBuilder The request builder * @param list The cookies * @param urlHost The URL host */ private void setCookies(final Builder requestConfigurationBuilder, final HttpClientBuilder httpClientBuilder, final List<HttpCookie> list, final String urlHost) { final CookieStore cookieStore = new BasicCookieStore(); final List<HttpCookie> cookies = list; for (final HttpCookie cookie : cookies) { final BasicClientCookie c = new BasicClientCookie(cookie.getName(), cookie.getValue()); c.setPath("/"); c.setVersion(0); c.setDomain(urlHost); cookieStore.addCookie(c); } httpClientBuilder.setDefaultCookieStore(cookieStore); requestConfigurationBuilder.setCookieSpec(CookieSpecs.BEST_MATCH); }
From source file:fr.eolya.utils.http.HttpLoader.java
public static Map<String, String> getAuthCookies(int authMode, String authLogin, String authPasswd, String authParam, String proxyHost, String proxyPort, String proxyExclude, String proxyUser, String proxyPassword) {// w ww . java2s . co m if (authMode == 0) return null; Map<String, String> authCookies = null; String[] aAuthParam = authParam.split("\\|"); // http://www.java-tips.org/other-api-tips/httpclient/how-to-use-http-cookies.html DefaultHttpClient httpClient = new DefaultHttpClient(); // Proxy setProxy(httpClient, aAuthParam[0], proxyHost, proxyPort, proxyExclude, proxyUser, proxyPassword); HttpPost httpPost = new HttpPost(aAuthParam[0]); httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); CookieStore cookieStore = new BasicCookieStore(); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); for (int i = 1; i < aAuthParam.length; i++) { String[] aPair = aAuthParam[i].split("="); aPair[1] = aPair[1].replaceAll("\\$\\$auth_login\\$\\$", authLogin); aPair[1] = aPair[1].replaceAll("\\$\\$auth_passwd\\$\\$", authPasswd); nameValuePairs.add(new BasicNameValuePair(aPair[0], aPair[1])); } httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); httpPost.setHeader("ContentType", "application/x-www-form-urlencoded"); HttpResponse response = httpClient.execute(httpPost, localContext); HttpEntity entity = response.getEntity(); if (entity != null) { entity.consumeContent(); } List<Cookie> cookies = httpClient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { authCookies = new HashMap<String, String>(); for (Cookie c : cookies) { // TODO: What about the path, the domain ??? authCookies.put(c.getName(), c.getValue()); } } httpPost.abort(); } catch (ClientProtocolException e) { return null; } catch (IOException e) { return null; } return authCookies; }