List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:intelligentWebAlgorithms.util.internet.crawling.transport.http.HTTPTransport.java
public void init() { P.println("Initializing HTTPTransport ..."); httpclient = new DefaultHttpClient(); // Create a local instance of cookie store cookieStore = new BasicCookieStore(); // Create local HTTP context localContext = new BasicHttpContext(); // Bind custom cookie store to the local context localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // httpclient.getHttpConnectionManager().getParams().setConnectionTimeout(30000); // httpclient.getHttpConnectionManager().getParams().setSoTimeout(30000); // httpclient.setState(initialState); // httpclient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY); ////from w w w .j ava2 s . c o m // //httpclient.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, // Boolean.TRUE); // // // Set default number of connections per host to 1 // httpclient.getHttpConnectionManager(). // getParams().setMaxConnectionsPerHost( // HostConfiguration.ANY_HOST_CONFIGURATION, 1); // // Set max for total number of connections // httpclient.getHttpConnectionManager().getParams().setMaxTotalConnections(10); }
From source file:com.farmafene.commons.cas.LoginTGT.java
/** * @return//w w w . j a v a 2s.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:org.eclipse.rdf4j.http.client.SPARQLProtocolSession.java
public SPARQLProtocolSession(HttpClient client, ExecutorService executor) { this.httpClient = client; this.httpContext = new HttpClientContext(); this.executor = executor; valueFactory = SimpleValueFactory.getInstance(); httpContext.setCookieStore(new BasicCookieStore()); // parser used for processing server response data should be lenient parserConfig.addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); parserConfig.addNonFatalError(BasicParserSettings.VERIFY_LANGUAGE_TAGS); // configure the maximum url length for SPARQL query GET requests int maximumUrlLength = DEFAULT_MAXIMUM_URL_LENGTH; String propertyValue = System.getProperty(MAXIMUM_URL_LENGTH_PARAM); if (propertyValue != null) { try {/*w w w .j a v a2 s. c o m*/ maximumUrlLength = Integer.parseInt(propertyValue); } catch (NumberFormatException e) { throw new RDF4JConfigException("integer value expected for property " + MAXIMUM_URL_LENGTH_PARAM, e); } } this.maximumUrlLength = maximumUrlLength; }
From source file:de.micromata.genome.tpsb.soapui.DelegateToSoapUiTestBuilderHttpClientRequestTransport.java
@Override public Response sendRequest(SubmitContext submitContext, Request request) throws Exception { boolean useSuper = false; if (useSuper == true) { return super.sendRequest(submitContext, request); }//from w w w.j a v a2 s .c om AbstractHttpRequestInterface<?> httpRequest = (AbstractHttpRequestInterface<?>) request; RequestMethod rm = httpRequest.getMethod(); ExtendedHttpMethod httpMethod; switch (rm) { case POST: { ExtendedPostMethod extendedPostMethod = new ExtendedPostMethod(); extendedPostMethod.setAfterRequestInjection(httpRequest.getAfterRequestInjection()); httpMethod = extendedPostMethod; break; } case GET: { ExtendedGetMethod extendedGetMethod = new ExtendedGetMethod(); // extendedGetMethod.setAfterRequestInjection(httpRequest.getAfterRequestInjection()); httpMethod = extendedGetMethod; break; } default: throw new IllegalArgumentException("Unsupported HTTP methd: " + rm); } HttpClientSupport.SoapUIHttpClient httpClient = HttpClientSupport.getHttpClient(); boolean createdContext = false; HttpContext httpContext = (HttpContext) submitContext.getProperty(SubmitContext.HTTP_STATE_PROPERTY); if (httpContext == null) { httpContext = new BasicHttpContext(); submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, httpContext); createdContext = true; // always use local cookie store so we don't share cookies with other threads/executions/requests CookieStore cookieStore = new BasicCookieStore(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); } String localAddress = System.getProperty("soapui.bind.address", httpRequest.getBindAddress()); if (localAddress == null || localAddress.trim().length() == 0) { localAddress = SoapUI.getSettings().getString(HttpSettings.BIND_ADDRESS, null); } org.apache.http.HttpResponse httpResponse = null; if (localAddress != null && localAddress.trim().length() > 0) { try { httpMethod.getParams().setParameter(ConnRoutePNames.LOCAL_ADDRESS, InetAddress.getByName(localAddress)); } catch (Exception e) { SoapUI.logError(e, "Failed to set localAddress to [" + localAddress + "]"); } } Map<String, String> httpRequestParameter = new HashMap<>(); if (httpRequest instanceof HttpTestRequest) { HttpTestRequest tr = (HttpTestRequest) httpRequest; for (String key : tr.getParams().keySet()) { RestParamProperty val = tr.getParams().get(key); String sval = val.getValue(); sval = PropertyExpander.expandProperties(submitContext, sval); httpRequestParameter.put(key, sval); } } submitContext.removeProperty(RESPONSE); submitContext.setProperty(HTTP_METHOD, httpMethod); submitContext.setProperty(POST_METHOD, httpMethod); submitContext.setProperty(HTTP_CLIENT, httpClient); submitContext.setProperty(REQUEST_CONTENT, httpRequest.getRequestContent()); submitContext.setProperty(WSDL_REQUEST, httpRequest); submitContext.setProperty(RESPONSE_PROPERTIES, new StringToStringMap()); List<RequestFilter> filters = getFilters(); for (RequestFilter filter : filters) { filter.filterRequest(submitContext, httpRequest); } try { Settings settings = httpRequest.getSettings(); // custom http headers last so they can be overridden StringToStringsMap headers = httpRequest.getRequestHeaders(); // first remove so we don't get any unwanted duplicates for (String header : headers.keySet()) { httpMethod.removeHeaders(header); } // now add for (String header : headers.keySet()) { for (String headerValue : headers.get(header)) { headerValue = PropertyExpander.expandProperties(submitContext, headerValue); httpMethod.addHeader(header, headerValue); } } // do request WsdlProject project = (WsdlProject) ModelSupport.getModelItemProject(httpRequest); WssCrypto crypto = null; if (project != null && project.getWssContainer() != null) { crypto = project.getWssContainer().getCryptoByName( PropertyExpander.expandProperties(submitContext, httpRequest.getSslKeystore())); } if (crypto != null && WssCrypto.STATUS_OK.equals(crypto.getStatus())) { httpMethod.getParams().setParameter(SoapUIHttpRoute.SOAPUI_SSL_CONFIG, crypto.getSource() + " " + crypto.getPassword()); } // dump file? httpMethod.setDumpFile(PathUtils.expandPath(httpRequest.getDumpFile(), (AbstractWsdlModelItem<?>) httpRequest, submitContext)); // include request time? if (settings.getBoolean(HttpSettings.INCLUDE_REQUEST_IN_TIME_TAKEN)) { httpMethod.initStartTime(); } if (httpMethod.getMetrics() != null) { httpMethod.getMetrics().setHttpMethod(httpMethod.getMethod()); PrivateBeanUtils.invokeMethod(this, "captureMetrics", httpMethod, httpClient); httpMethod.getMetrics().getTotalTimer().start(); } // submit! httpResponse = execute(submitContext, httpMethod, httpContext, httpRequestParameter); if (httpMethod.getMetrics() != null) { httpMethod.getMetrics().getReadTimer().stop(); httpMethod.getMetrics().getTotalTimer().stop(); } // if (isRedirectResponse(httpResponse.getStatusLine().getStatusCode()) && httpRequest.isFollowRedirects()) { // if (httpResponse.getEntity() != null) { // EntityUtils.consume(httpResponse.getEntity()); // } // // ExtendedGetMethod returnMethod = followRedirects(httpClient, 0, httpMethod, httpResponse, httpContext); // httpMethod = returnMethod; // submitContext.setProperty(HTTP_METHOD, httpMethod); // } } catch (Throwable t) { // NOSONAR "Illegal Catch" framework httpMethod.setFailed(t); if (t instanceof Exception) { throw (Exception) t; } SoapUI.logError(t); throw new Exception(t); } finally { if (!httpMethod.isFailed()) { if (httpMethod.getMetrics() != null) { if (httpMethod.getMetrics().getReadTimer().getStop() == 0) { httpMethod.getMetrics().getReadTimer().stop(); } if (httpMethod.getMetrics().getTotalTimer().getStop() == 0) { httpMethod.getMetrics().getTotalTimer().stop(); } } } else { httpMethod.getMetrics().reset(); httpMethod.getMetrics().setTimestamp(System.currentTimeMillis()); // captureMetrics(httpMethod, httpClient); } for (int c = filters.size() - 1; c >= 0; c--) { RequestFilter filter = filters.get(c); filter.afterRequest(submitContext, httpRequest); } if (!submitContext.hasProperty(RESPONSE)) { createDefaultResponse(submitContext, httpRequest, httpMethod); } Response response = (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE); StringToStringMap responseProperties = (StringToStringMap) submitContext .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES); for (String key : responseProperties.keySet()) { response.setProperty(key, responseProperties.get(key)); } if (createdContext) { submitContext.setProperty(SubmitContext.HTTP_STATE_PROPERTY, null); } } return (Response) submitContext.getProperty(BaseHttpRequestTransport.RESPONSE); }
From source file:ti.modules.titanium.network.NetworkModule.java
public static CookieStore getHTTPCookieStoreInstance() { if (httpCookieStore == null) { httpCookieStore = new BasicCookieStore(); }//www . j a v a 2 s . c o m return httpCookieStore; }
From source file:com.github.lpezet.antiope.dao.DefaultHttpClientFactory.java
@Override public HttpClient createHttpClient(APIConfiguration pConfiguration) { // Use a custom connection factory to customize the process of // initialization of outgoing HTTP connections. Beside standard connection // configuration parameters HTTP connection factory can define message // parser / writer routines to be employed by individual connections. HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory( new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory()); SSLContext oSslContext = null; X509HostnameVerifier oHostnameVerifier = null; if (pConfiguration.isCheckSSLCertificates()) { oSslContext = SSLContexts.createSystemDefault(); oHostnameVerifier = new BrowserCompatHostnameVerifier(); } else {// w w w. j a v a2s. co m final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) { } @Override public X509Certificate[] getAcceptedIssuers() { return null; } } }; // Install the all-trusting trust manager try { final SSLContext sslContext = SSLContext.getInstance(SSL); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); // Create an ssl socket factory with our all-trusting manager //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory(); oSslContext = sslContext; } catch (NoSuchAlgorithmException e) { throw new APIClientException(e); } catch (KeyManagementException e) { throw new APIClientException(e); } oHostnameVerifier = new AllowAllHostnameVerifier(); } // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register(HTTP, PlainConnectionSocketFactory.INSTANCE) .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build(); // Use custom DNS resolver to override the system DNS resolution. DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* { @Override public InetAddress[] resolve(final String host) throws UnknownHostException { if (host.equalsIgnoreCase("myhost")) { return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) }; } else { return super.resolve(host); } } };*/ // Create a connection manager with custom configuration. PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager( oSocketFactoryRegistry, oConnFactory, oDnsResolver); // Create socket configuration SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true) .setSoTimeout(pConfiguration.getSocketTimeout()).build(); // Configure the connection manager to use socket configuration either // by default or for a specific host. oConnManager.setDefaultSocketConfig(oSocketConfig); // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig); // Create message constraints MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200) .setMaxLineLength(2000).build(); // Create connection configuration ConnectionConfig oConnectionConfig = ConnectionConfig.custom() .setMalformedInputAction(CodingErrorAction.IGNORE) .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8) .setMessageConstraints(oMessageConstraints).build(); // Configure the connection manager to use connection configuration either // by default or for a specific host. oConnManager.setDefaultConnectionConfig(oConnectionConfig); // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT); // Configure total max or per route limits for persistent connections // that can be kept in the pool or leased by the connection manager. oConnManager.setMaxTotal(100); oConnManager.setDefaultMaxPerRoute(10); //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20); // Use custom cookie store if necessary. CookieStore oCookieStore = new BasicCookieStore(); // Use custom credentials provider if necessary. // // Create global request configuration RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) //.setExpectContinueEnabled(true) // WARNING: setting it to true slows things down by 4s!!!! .setStaleConnectionCheckEnabled(true) .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)) .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)) .setConnectTimeout(pConfiguration.getConnectionTimeout()).build(); CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider(); HttpHost oProxy = null; if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) { String proxyHost = pConfiguration.getProxyHost(); int proxyPort = pConfiguration.getProxyPort(); String proxyUsername = pConfiguration.getProxyUsername(); String proxyPassword = pConfiguration.getProxyPassword(); String proxyDomain = pConfiguration.getProxyDomain(); String proxyWorkstation = pConfiguration.getProxyWorkstation(); oProxy = new HttpHost(proxyHost, proxyPort); if (proxyUsername != null && proxyPassword != null) { oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort), new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain)); } } // Create an HttpClient with the given custom dependencies and configuration. CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager) .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider) .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build(); return oHttpClient; /* RequestConfig oRequestConfig = RequestConfig.custom() .setConnectTimeout(pConfiguration.getConnectionTimeout()) .setSocketTimeout(pConfiguration.getSocketTimeout()) .setStaleConnectionCheckEnabled(true) .build(); */ }
From source file:org.wso2.carbon.governance.registry.extensions.executors.apistore.ApiStore2Executor.java
/** * Update the APIM DB for the published API. * * @param resource// w w w. j a v a 2 s .c o m * @param serviceName */ private boolean publishDataToAPIM(Resource resource, String serviceName) throws GovernanceException { boolean valid = true; if (apimEndpoint == null || apimUsername == null || apimPassword == null || apimEnv == null) { throw new GovernanceException(ExecutorConstants.APIM_LOGIN_UNDEFINED); } CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); String sessionCookie = APIUtils.authenticateAPIM_2(httpContext, apimEndpoint, apimUsername, apimPassword); String addAPIendpoint = apimEndpoint + Constants.APIM_2_0_0_ENDPOINT; try { // create a post request to addAPI. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(addAPIendpoint); httppost.setHeader("Cookie", "JSESSIONID=" + sessionCookie); // Request parameters and other properties. List<NameValuePair> params = new ArrayList<NameValuePair>(); addParameters(params, resource, serviceName); LOG.info(new UrlEncodedFormEntity(params, Constants.UTF_8_ENCODE)); APIUtils.callAPIMToPublishAPI2(httpclient, httppost, params, httpContext); } catch (Exception e) { LOG.error("Exception occurred while publishing to APIM", e); throw new GovernanceException(e.getMessage(), e); } return valid; }
From source file:org.wildfly.elytron.web.undertow.server.FormAuthenticationWithClusteredSSOTest.java
@Test public void testSessionInvalidation() throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri()))); for (int i = 0; i < 10; i++) { HttpPost httpAuthenticate = new HttpPost(serverA.createUri("/j_security_check")); List<NameValuePair> parameters = new ArrayList<>(2); parameters.add(new BasicNameValuePair("j_username", "ladybird")); parameters.add(new BasicNameValuePair("j_password", "Coleoptera")); httpAuthenticate.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse execute = httpClient.execute(httpAuthenticate); assertSuccessfulResponse(execute, "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverA.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverB.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverC.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverD.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverE.createUri())), "ladybird"); httpClient.execute(new HttpGet(serverA.createUri("/logout"))); assertLoginPage(httpClient.execute(new HttpGet(serverC.createUri()))); assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri()))); assertLoginPage(httpClient.execute(new HttpGet(serverB.createUri()))); assertLoginPage(httpClient.execute(new HttpGet(serverD.createUri()))); assertLoginPage(httpClient.execute(new HttpGet(serverE.createUri()))); }/*from w w w.j a v a2 s. co m*/ this.sessionManagers.values().forEach( manager -> assertEquals(manager.getDeploymentName(), 1, manager.getActiveSessions().size())); }