List of usage examples for org.apache.http.impl.client HttpClients custom
public static HttpClientBuilder custom()
From source file:org.ops4j.pax.web.itest.DigestAuthenticationTest.java
@Test public void shouldDenyAccessOnWrongPassword() throws Exception { assertThat(servletContext.getContextPath(), is("/digest")); String path = String.format("http://localhost:%d/digest/hello", getHttpPort()); HttpClientContext context = HttpClientContext.create(); BasicCredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("mustermann", "wrong")); CloseableHttpClient client = HttpClients.custom().setDefaultCredentialsProvider(cp).build(); HttpGet httpGet = new HttpGet(path); HttpResponse response = client.execute(httpGet, context); int statusCode = response.getStatusLine().getStatusCode(); assertThat(statusCode, is(401));/*from w w w. ja v a 2s . co m*/ }
From source file:org.superbiz.CdiEventRealmTest.java
@Test public void notAuthorized() throws IOException { final BasicCookieStore cookieStore = new BasicCookieStore(); final CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); // first authenticate with the login servlet final HttpPost httpPost = new HttpPost(webapp.toExternalForm() + "login"); final List<NameValuePair> data = new ArrayList<NameValuePair>() { {//from w w w . jav a2 s. c om add(new BasicNameValuePair("username", "userB")); add(new BasicNameValuePair("password", "secret")); } }; httpPost.setEntity(new UrlEncodedFormEntity(data)); final CloseableHttpResponse respLogin = client.execute(httpPost); try { assertEquals(200, respLogin.getStatusLine().getStatusCode()); } finally { respLogin.close(); } // then we can just call the hello servlet final HttpGet httpGet = new HttpGet(webapp.toExternalForm() + "hello"); final CloseableHttpResponse resp = client.execute(httpGet); try { assertEquals(403, resp.getStatusLine().getStatusCode()); } finally { resp.close(); } }
From source file:sabina.integration.TestScenario.java
TestScenario(String backend, int port, boolean secure, boolean externalFiles) { this.port = port; this.backend = backend; this.secure = secure; this.externalFiles = externalFiles; SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslFactory(), ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", sslConnectionSocketFactory).build(); HttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(socketFactoryRegistry, new ManagedHttpClientConnectionFactory()); RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.NETSCAPE).build(); cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); context.setCookieStore(cookieStore); this.httpClient = HttpClients.custom().setSchemePortResolver(h -> { Args.notNull(h, "HTTP host"); final int port1 = h.getPort(); if (port1 > 0) { return port1; }//www . j av a2 s . co m final String name = h.getSchemeName(); if (name.equalsIgnoreCase("http")) { return port1; } else if (name.equalsIgnoreCase("https")) { return port1; } else { throw new UnsupportedSchemeException("unsupported protocol: " + name); } }).setConnectionManager(connManager).setDefaultRequestConfig(globalConfig).build(); }
From source file:com.jaspersoft.studio.server.protocol.restv2.CASUtil.java
public static String doGetTocken(ServerProfile sp, SSOServer srv, IProgressMonitor monitor) throws Exception { SSLContext sslContext = SSLContext.getInstance("SSL"); // set up a TrustManager that trusts everything sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { // System.out.println("getAcceptedIssuers ============="); return null; }/* w ww . jav a2s. c o m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { // System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String arg0) { // TODO Auto-generated method stub return super.isRedirectable(arg0); } @Override public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context) throws ProtocolException { // TODO Auto-generated method stub return super.isRedirected(request, response, context); } }).setDefaultCookieStore(new BasicCookieStore()) .setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0") .build(); Executor exec = Executor.newInstance(httpclient); URIBuilder ub = new URIBuilder(sp.getUrl() + "index.html"); String fullURL = ub.build().toASCIIString(); Request req = HttpUtils.get(fullURL, sp); HttpHost proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); String tgtID = readData(exec, req, monitor); String action = getFormAction(tgtID); if (action != null) { action = action.replaceFirst("/", ""); int indx = action.indexOf(";jsession"); if (indx >= 0) action = action.substring(0, indx); } else action = "cas/login"; String url = srv.getUrl(); if (!url.endsWith("/")) url += "/"; ub = new URIBuilder(url + action); // fullURL = ub.build().toASCIIString(); req = HttpUtils.get(fullURL, sp); proxy = net.sf.jasperreports.eclipse.util.HttpUtils.getUnauthProxy(exec, new URI(fullURL)); if (proxy != null) req.viaProxy(proxy); tgtID = readData(exec, req, monitor); action = getFormAction(tgtID); action = action.replaceFirst("/", ""); ub = new URIBuilder(url + action); Map<String, String> map = getInputs(tgtID); Form form = Form.form(); for (String key : map.keySet()) { if (key.equals("btn-reset")) continue; else if (key.equals("username")) { form.add(key, srv.getUser()); continue; } else if (key.equals("password")) { form.add(key, Pass.getPass(srv.getPassword())); continue; } form.add(key, map.get(key)); } // req = HttpUtils.post(ub.build().toASCIIString(), form, sp); if (proxy != null) req.viaProxy(proxy); // Header header = null; readData(exec, req, monitor); // for (Header h : headers) { // for (HeaderElement he : h.getElements()) { // if (he.getName().equals("CASTGC")) { // header = new BasicHeader("Cookie", h.getValue()); // break; // } // } // } ub = new URIBuilder(url + action); url = sp.getUrl(); if (!url.endsWith("/")) url += "/"; ub.addParameter("service", url + "j_spring_security_check"); req = HttpUtils.get(ub.build().toASCIIString(), sp); if (proxy != null) req.viaProxy(proxy); // req.addHeader("Accept", // "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8, value"); req.addHeader("Referrer", sp.getUrl()); // req.addHeader(header); String html = readData(exec, req, monitor); Matcher matcher = ahrefPattern.matcher(html); while (matcher.find()) { Map<String, String> attributes = parseAttributes(matcher.group(1)); String v = attributes.get("href"); int ind = v.indexOf("ticket="); if (ind > 0) { return v.substring(ind + "ticket=".length()); } } return null; }
From source file:com.yahoo.yrlhaifa.liveqa.challenge.http_operation.QuestionOperationHttpRequestSender.java
public void sendRequestsAndCollectAnswers() throws QuestionOperationException, InterruptedException { if (mapParticipantToAnswer.size() > 0) { throw new QuestionOperationException("BUG: The given map from system-id to answers is not empty."); }//from w w w. j a v a 2 s .c o m CloseableHttpClient httpClient = HttpClients.custom().setMaxConnPerRoute(participants.size()).build(); try { ExecutorService executor = Executors.newFixedThreadPool(participants.size()); try { FutureRequestExecutionService requestExecutor = new FutureRequestExecutionService(httpClient, executor); logger.info("Sending requests using request-executor..."); sendRequestsWithRequestExecutor(requestExecutor); logger.info("Sending requests using request-executor - done."); } finally { try { executor.shutdownNow(); } catch (RuntimeException e) { // TODO Add more error handling logger.error("Failed to shutdown executor. Program continues.", e); } } } finally { try { httpClient.close(); } catch (IOException | RuntimeException e) { // TODO Add more error handling logger.error("Failed to close HTTP client. Program continues.", e); } } // Remove those who did not finish on time, but did write results. Set<Participant> didNotSucceed = new LinkedHashSet<Participant>(); for (Participant participant : mapParticipantToAnswer.keySet()) { if (!(systemsSucceeded.contains(participant))) { didNotSucceed.add(participant); } } for (Participant toRemove : didNotSucceed) { mapParticipantToAnswer.remove(toRemove); } if (exception != null) { throw exception; } }
From source file:org.createnet.raptor.auth.AuthHttpClient.java
private CloseableHttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException, UnrecoverableKeyException, CertificateException, IOException { if (httpclient == null) { logger.debug("Created http client instance"); // Trust own CA and all self-signed certs SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(new File(config.token.truststore.path), config.token.truststore.password.toCharArray(), new TrustSelfSignedStrategy()).build(); // Allow TLSv1 protocol only SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1.2", "TLSv1.1", "TLSv1" }, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier()); Registry socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE).register("https", sslsf).build(); HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry);/*from ww w . j a v a 2 s. c o m*/ httpclient = HttpClients.custom() // .setSSLSocketFactory(sslsf) .setConnectionManager(poolingConnManager) // .setConnectionManagerShared(true) .build(); } return httpclient; }
From source file:org.wisdom.framework.filters.ProxyFilter.java
/** * Allows you do override the HTTP Client used to execute the requests. * By default, it used a custom client without cookies. * * @return the HTTP Client instance/*from w ww . j a va2 s .c om*/ */ protected HttpClient newHttpClient() { return HttpClients.custom() // Do not manage redirection. .setRedirectStrategy(new DefaultRedirectStrategy() { @Override protected boolean isRedirectable(String method) { return followRedirect(method); } }).setDefaultCookieStore(new BasicCookieStore() { @Override public synchronized List<Cookie> getCookies() { return Collections.emptyList(); } }).build(); }
From source file:io.seldon.external.ExternalPredictionServer.java
@Autowired public ExternalPredictionServer(GlobalConfigHandler globalConfigHandler, ClientRpcStore rpcStore) { cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(150);/*from w w w . j ava 2s.co m*/ cm.setDefaultMaxPerRoute(150); RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(DEFAULT_REQ_TIMEOUT) .setConnectTimeout(DEFAULT_CON_TIMEOUT).setSocketTimeout(DEFAULT_SOCKET_TIMEOUT).build(); httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig).build(); globalConfigHandler.addSubscriber(ZK_CONFIG_TEMP, this); this.rpcStore = rpcStore; }
From source file:org.apache.juneau.rest.test.TestMicroservice.java
public static CloseableHttpClient createHttpClient() { try {//from w w w . j av a 2 s .c o m return HttpClients.custom().setSSLSocketFactory(getSSLSocketFactory()) .setRedirectStrategy(new LaxRedirectStrategy()).build(); } catch (Exception e) { throw new RuntimeException(e); } }