List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultCredentialsProvider
public final HttpClientBuilder setDefaultCredentialsProvider(final CredentialsProvider credentialsProvider)
From source file:org.jboss.teiid.quickstart.PortfolioHTTPClient.java
public static void main(String[] args) throws URISyntaxException, UnsupportedEncodingException { String hostname = "localhost"; int port = 8080; String username = "restUser"; String password = "password1!"; if (args.length == 4) { hostname = args[0];/*from w ww.j a v a 2 s .co m*/ port = Integer.parseInt(args[1]); username = args[2]; password = args[3]; } HttpClientBuilder builder = HttpClientBuilder.create(); HttpHost targetHost = new HttpHost(hostname, port); CredentialsProvider credsProvider = new BasicCredentialsProvider(); AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password); credsProvider.setCredentials(scope, credentials); builder.setDefaultCredentialsProvider(credsProvider); HttpClient client = builder.build(); execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/foo/1")); execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/getAllStocks")); execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/getAllStockById/1007")); execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/getAllStockBySymbol/IBM")); }
From source file:be.dnsbelgium.rdap.client.RDAPCLI.java
public static void main(String[] args) { LOGGER.debug("Create the command line parser"); CommandLineParser parser = new GnuParser(); LOGGER.debug("Create the options"); Options options = new RDAPOptions(Locale.ENGLISH); try {//from ww w . j av a 2 s. co m LOGGER.debug("Parse the command line arguments"); CommandLine line = parser.parse(options, args); if (line.hasOption("help")) { printHelp(options); return; } if (line.getArgs().length == 0) { throw new IllegalArgumentException("You must provide a query"); } String query = line.getArgs()[0]; Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase()) : guessQueryType(query); LOGGER.debug("Query: {}, Type: {}", query, type); try { SSLContextBuilder sslContextBuilder = SSLContexts.custom(); if (line.hasOption(RDAPOptions.TRUSTSTORE)) { sslContextBuilder.loadTrustMaterial( RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)), line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE), line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS))); } if (line.hasOption(RDAPOptions.KEYSTORE)) { sslContextBuilder.loadKeyMaterial( RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)), line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE), line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)), line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray()); } SSLContext sslContext = sslContextBuilder.build(); final String url = line.getOptionValue(RDAPOptions.URL); final HttpHost host = Utils.httpHost(url); HashSet<Header> headers = new HashSet<Header>(); headers.add(new BasicHeader("Accept-Language", line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString()))); HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers) .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext, (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier()))); if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) { BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()), new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME), line.getOptionValue(RDAPOptions.PASSWORD))); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url); ObjectMapper mapper = new ObjectMapper(); JsonNode json = null; switch (type) { case DOMAIN: json = rdapClient.getDomainAsJson(query); break; case ENTITY: json = rdapClient.getEntityAsJson(query); break; case AUTNUM: json = rdapClient.getAutNum(query); break; case IP: json = rdapClient.getIp(query); break; case NAMESERVER: json = rdapClient.getNameserver(query); break; } PrintWriter out = new PrintWriter(System.out, true); if (line.hasOption(RDAPOptions.RAW)) { mapper.writer().writeValue(out, json); } else if (line.hasOption(RDAPOptions.PRETTY)) { mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json); } else if (line.hasOption(RDAPOptions.YAML)) { DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setPrettyFlow(true); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); dumperOptions.setSplitLines(true); Yaml yaml = new Yaml(dumperOptions); Map data = mapper.convertValue(json, Map.class); yaml.dump(data, out); } else { mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json); } out.flush(); } catch (Exception e) { LOGGER.error(e.getMessage(), e); System.exit(-1); } } catch (org.apache.commons.cli.ParseException e) { printHelp(options); System.exit(-1); } }
From source file:com.ibm.watson.retrieveandrank.app.rest.UtilityFunctions.java
public static HttpClientBuilder createHTTPBuilder(URI uri, String username, String password) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()), new UsernamePasswordCredentials(username, password)); final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32) .setDefaultRequestConfig(// w w w . jav a 2 s . c o m RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build()); builder.setDefaultCredentialsProvider(credentialsProvider); builder.addInterceptorFirst(new PreemptiveAuthInterceptor()); return builder; }
From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java
@Bean public static RestTemplate getTemplate() throws IOException { if (template == null) { CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT), new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD)); Header[] h = new Header[3]; h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"); h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN); List<Header> headers = new ArrayList<>(Arrays.asList(h)); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.useSystemProperties(); clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT)); clientBuilder.setDefaultCredentialsProvider(credentialsProvider); clientBuilder.setDefaultHeaders(headers).build(); String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv"; HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build(); clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); CloseableHttpClient client = clientBuilder.build(); client.execute(request);//from w w w. ja v a2 s .c om HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(); factory.setHttpClient(client); template = new RestTemplate(); template.setRequestFactory(factory); } return template; }
From source file:com.ibm.ecod.watson.RetrieveAndRankSolrJExample.java
private static HttpClient createHttpClient(String uri, String username, String password) { final URI scopeUri = URI.create(uri); final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()), new UsernamePasswordCredentials(username, password)); final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32) .setDefaultRequestConfig(/*from w ww .j a v a 2s . c om*/ RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build()); builder.setDefaultCredentialsProvider(credentialsProvider); return builder.build(); }
From source file:org.jboss.as.test.http.util.TestHttpClientUtils.java
/** *@param credentialsProvider optional cred provider * @return client that doesn't verify https connections *//*from w ww. j a v a 2 s . c o m*/ public static CloseableHttpClient getHttpsClient(CredentialsProvider credentialsProvider) { try { SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return null; } }; ctx.init(null, new TrustManager[] { tm }, null); ctx.init(null, new TrustManager[] { tm }, null); SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(ctx, new NoopHostnameVerifier()); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnectionFactory).build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); HttpClientBuilder builder = HttpClientBuilder.create().setSSLSocketFactory(sslConnectionFactory) .setSSLHostnameVerifier(new NoopHostnameVerifier()).setConnectionManager(ccm); if (credentialsProvider != null) { builder.setDefaultCredentialsProvider(credentialsProvider); } return builder.build(); } catch (Exception ex) { ex.printStackTrace(); return null; } }
From source file:org.nuxeo.connect.connector.http.ProxyHelper.java
public static void configureProxyIfNeeded(HttpClientBuilder httpClientBuilder, String url) { RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, url); httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); }
From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java
public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception { CloseableHttpClient httpClient = null; try {//ww w .j a v a 2 s .c o m CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", idpPort), new UsernamePasswordCredentials(user, password)); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks")); try { trustStore.load(instream, "clientpass".toCharArray()); } finally { try { instream.close(); } catch (Exception ex) { ex.printStackTrace(); } } SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()); sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray()); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); httpClientBuilder.setDefaultCredentialsProvider(credsProvider); httpClientBuilder.setSSLSocketFactory(sslSocketFactory); httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy()); httpClient = httpClientBuilder.build(); HttpGet httpget = new HttpGet(url); HttpResponse response = httpClient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println(response.getStatusLine()); if (entity != null) { System.out.println("Response content length: " + entity.getContentLength()); } Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: " + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode()); return EntityUtils.toString(entity); } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources if (httpClient != null) { httpClient.close(); } } }
From source file:org.springframework.cloud.deployer.admin.shell.command.support.HttpClientUtils.java
/** * Ensures that the passed-in {@link RestTemplate} is using the Apache HTTP Client. If the optional {@code username} AND * {@code password} are not empty, then a {@link BasicCredentialsProvider} will be added to the {@link CloseableHttpClient}. * * Furthermore, you can set the underlying {@link SSLContext} of the {@link HttpClient} allowing you to accept self-signed * certificates.//w w w . ja va 2 s . c om * * @param restTemplate Must not be null * @param username Can be null * @param password Can be null * @param skipSslValidation Use with caution! If true certificate warnings will be ignored. */ public static void prepareRestTemplate(RestTemplate restTemplate, String username, String password, boolean skipSslValidation) { Assert.notNull(restTemplate, "The provided RestTemplate must not be null."); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (StringUtils.hasText(username) && StringUtils.hasText(password)) { final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password)); httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider); } if (skipSslValidation) { httpClientBuilder.setSSLContext(HttpClientUtils.buildCertificateIgnoringSslContext()); httpClientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier()); } final CloseableHttpClient httpClient = httpClientBuilder.build(); final HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient); restTemplate.setRequestFactory(requestFactory); }
From source file:io.fabric8.maven.support.Apps.java
/** * Posts a file to the git repository/*w ww. ja va 2s . com*/ */ public static HttpResponse postFileToGit(File file, String user, String password, String consoleUrl, String branch, String path, Logger logger) throws URISyntaxException, IOException { HttpClientBuilder builder = HttpClients.custom(); if (Strings.isNotBlank(user) && Strings.isNotBlank(password)) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials(user, password)); builder = builder.setDefaultCredentialsProvider(credsProvider); } CloseableHttpClient client = builder.build(); try { String url = consoleUrl; if (!url.endsWith("/")) { url += "/"; } url += "git/"; url += branch; if (!path.startsWith("/")) { url += "/"; } url += path; logger.info("Posting App Zip " + file.getName() + " to " + url); URI buildUrl = new URI(url); HttpPost post = new HttpPost(buildUrl); // use multi part entity format FileBody zip = new FileBody(file); HttpEntity entity = MultipartEntityBuilder.create().addPart(file.getName(), zip).build(); post.setEntity(entity); // post.setEntity(new FileEntity(file)); HttpResponse response = client.execute(URIUtils.extractHost(buildUrl), post); logger.info("Response: " + response); if (response != null) { int statusCode = response.getStatusLine().getStatusCode(); if (statusCode < 200 || statusCode >= 300) { throw new IllegalStateException("Failed to post App Zip to: " + url + " " + response); } } return response; } finally { Closeables.closeQuietly(client); } }