List of usage examples for org.apache.http.impl.client HttpClientBuilder build
public CloseableHttpClient build()
From source file:com.github.hexsmith.spring.boot.rest.client.ApacheHttpClient.java
public static void main(String[] args) { HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); HttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); RestTemplate restTemplate = new RestTemplate(factory); User user = restTemplate.getForObject("http://localhost:8080/json/user", User.class); System.out.println(user);/* w w w . jav a2 s.c o m*/ }
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];/* w w w . j av a 2 s.c o 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:simauthenticator.SimAuthenticator.java
/** * @param args the command line arguments *//*from ww w . j a v a 2 s. c o m*/ public static void main(String[] args) throws Exception { cliOpts = new Options(); cliOpts.addOption("U", "url", true, "Connection URL"); cliOpts.addOption("u", "user", true, "User name"); cliOpts.addOption("p", "password", true, "User password"); cliOpts.addOption("d", "domain", true, "Domain name"); cliOpts.addOption("v", "verbose", false, "Verbose output"); cliOpts.addOption("k", "keystore", true, "KeyStore path"); cliOpts.addOption("K", "keystorepass", true, "KeyStore password"); cliOpts.addOption("h", "help", false, "Print help info"); CommandLineParser clip = new GnuParser(); cmd = clip.parse(cliOpts, args); if (cmd.hasOption("help")) { help(); return; } else { boolean valid = init(args); if (!valid) { return; } } HttpClientContext clientContext = HttpClientContext.create(); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); char[] keystorePassword = passwk.toCharArray(); FileInputStream kfis = null; try { kfis = new FileInputStream(keyStorePath); ks.load(kfis, keystorePassword); } finally { if (kfis != null) { kfis.close(); } } SSLContext sslContext = SSLContexts.custom().useSSL().loadTrustMaterial(ks).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setSslcontext(sslContext) .setSSLSocketFactory(sslsf).setUserAgent(userAgent); ; cookieStore = new BasicCookieStore(); /* BasicClientCookie cookie = new BasicClientCookie("SIM authenticator", "Utility for getting event details"); cookie.setVersion(0); cookie.setDomain(".astelit.ukr"); cookie.setPath("/"); cookieStore.addCookie(cookie);*/ CloseableHttpClient client = httpClientBuilder.build(); try { NTCredentials creds = new NTCredentials(usern, passwu, InetAddress.getLocalHost().getHostName(), domain); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, creds); HttpClientContext context = HttpClientContext.create(); context.setCredentialsProvider(credsProvider); context.setCookieStore(cookieStore); HttpGet httpget = new HttpGet(eventUrl); if (verbose) { System.out.println("executing request " + httpget.getRequestLine()); } HttpResponse response = client.execute(httpget, context); HttpEntity entity = response.getEntity(); HttpPost httppost = new HttpPost(eventUrl); List<Cookie> cookies = cookieStore.getCookies(); if (verbose) { System.out.println("----------------------------------------------"); System.out.println(response.getStatusLine()); System.out.print("Initial set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("usernameInput", usern)); nvps.add(new BasicNameValuePair("passwordInput", passwu)); nvps.add(new BasicNameValuePair("domainInput", domain)); //nvps.add(new BasicNameValuePair("j_username", domain + "\\" + usern)); //nvps.add(new BasicNameValuePair("j_password", ipAddr + ";" + passwu)); if (entity != null && verbose) { System.out.println("Responce content length: " + entity.getContentLength()); } //System.out.println(EntityUtils.toString(entity)); httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8)); HttpResponse afterPostResponse = client.execute(httppost, context); HttpEntity afterPostEntity = afterPostResponse.getEntity(); cookies = cookieStore.getCookies(); if (entity != null && verbose) { System.out.println("----------------------------------------------"); System.out.println(afterPostResponse.getStatusLine()); System.out.println("Responce content length: " + afterPostEntity.getContentLength()); System.out.print("After POST set of cookies: "); if (cookies.isEmpty()) { System.out.println("none"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } } System.out.println(EntityUtils.toString(afterPostEntity)); EntityUtils.consume(entity); EntityUtils.consume(afterPostEntity); } finally { client.getConnectionManager().shutdown(); } }
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 w w w. ja va 2 s. com*/ 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:org.cloudfoundry.identity.uaa.util.UaaHttpRequestUtils.java
protected static ClientHttpRequestFactory createRequestFactory(HttpClientBuilder builder) { return new HttpComponentsClientHttpRequestFactory(builder.build()); }
From source file:com.yoelnunez.mobilefirst.analytics.AnalyticsAPI.java
public static AnalyticsAPI createInstance(AppContext context) throws MissingServerContextException { if (serverContext == null) { throw new MissingServerContextException("Server context missing, analytics reporting will fail."); }/*from w w w .j a va2 s . c o m*/ if (httpClient == null) { HttpClientBuilder builder = HttpClientBuilder.create(); httpClient = builder.build(); } logs = new HashMap<JSONObject, JSONArray>(); return new AnalyticsAPI(context); }
From source file:com.questdb.test.tools.HttpTestUtils.java
public static void download(HttpClientBuilder b, String url, File out) throws IOException { try (CloseableHttpClient client = b.build(); CloseableHttpResponse r = client.execute(new HttpGet(url)); FileOutputStream fos = new FileOutputStream(out)) { copy(r.getEntity().getContent(), fos); }/* ww w . j a v a 2s . c o m*/ }
From source file:com.comcast.viper.hlsparserj.PlaylistFactory.java
/** * Factory method to generate playlist object. This method uses a very * simple HTTP client to download the URL passed by the playlistURL * parameters. This method should not be used for applications that require * high-performance, as the HTTP connection management is very basic. If * your application has high performance requirements us the parsePlaylist * method that takes an InputStream./*from www . j a va 2s . com*/ * * @param playlistVersion version of the playlist (V12 is the default) * @param playlistURL URL pointing to a playlist * @return parsed playlist * @throws IOException on connection and parsing exceptions */ public static AbstractPlaylist parsePlaylist(final PlaylistVersion playlistVersion, final URL playlistURL) throws IOException { HttpClientBuilder builder = HttpClientBuilder.create(); CloseableHttpClient httpClient = builder.build(); PlaylistParser parser = new PlaylistParser(); try { InputStream playlistStream = getPlaylistInputStream(httpClient, playlistURL); parser.parse(playlistStream); } finally { httpClient.close(); } return getVersionSpecificPlaylist(parser, playlistVersion); }
From source file:sk.datalan.solr.impl.HttpClientUtil.java
/** * Creates new http client by using the provided configuration. * * @param config http client configuration, if null a client with default configuration (no additional * configuration) is created./*w w w . ja v a2s.c om*/ * @return http client instance */ public static CloseableHttpClient createClient(final HttpClientConfiguration config) { if (log.isDebugEnabled()) { log.debug("Creating new http client, config:" + config); } HttpClientBuilder clientBuilder = configureClient(config); return clientBuilder.build(); }
From source file:com.liferay.mobile.android.http.file.DownloadUtil.java
public static void download(Session session, OutputStream os, String URL, FileProgressCallback callback) throws Exception { HttpClientBuilder clientBuilder = HttpUtil.getClientBuilder(session); HttpGetHC4 request = HttpUtil.getHttpGet(session, URL); HttpResponse response = clientBuilder.build().execute(request); HttpUtil.checkStatusCode(request, response); InputStream is = response.getEntity().getContent(); try {//from ww w. j a va 2 s . c o m transfer(request, is, os, callback); } finally { close(is); } }