List of usage examples for org.apache.http.impl.client HttpClientBuilder create
public static HttpClientBuilder create()
From source file:org.ligoj.app.http.security.DigestAuthenticationFilter.java
@Override public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response) { final String token = request.getParameter("token"); if (token != null) { // Token is the last part of URL // First get the cookie final HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig( RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build()); // Do the POST try (CloseableHttpClient httpClient = clientBuilder.build()) { final HttpPost httpPost = new HttpPost(getSsoPostUrl()); httpPost.setEntity(new StringEntity(token, StandardCharsets.UTF_8.name())); httpPost.setHeader("Content-Type", "application/json"); final HttpResponse httpResponse = httpClient.execute(httpPost); if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) { return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken( EntityUtils.toString(httpResponse.getEntity()), "N/A", new ArrayList<>())); }/*w w w . j a va2 s. c o m*/ } catch (final IOException e) { log.warn("Local SSO server is not available", e); } } throw new BadCredentialsException("Invalid user or password"); }
From source file:org.exmaralda.webservices.BASWebServiceResult.java
public String getDownloadText() throws IOException { StringBuilder result = new StringBuilder(); HttpClient client = HttpClientBuilder.create().build(); // new DefaultHttpClient(); HttpGet request = new HttpGet(downloadLink); request.addHeader("http.protocol.content-charset", "UTF-8"); HttpResponse response = client.execute(request); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent(), "UTF-8")); String sCurrentLine;/*from w w w. j a v a 2 s . co m*/ while ((sCurrentLine = rd.readLine()) != null) { result.append(sCurrentLine); result.append("\n"); } } else { // something went wrong, throw an exception String reason = statusLine.getReasonPhrase(); throw new IOException(reason); } return result.toString(); }
From source file:sk.datalan.solr.impl.HttpClientUtil.java
public static HttpClientBuilder configureClient(final HttpClientConfiguration config) { HttpClientBuilder clientBuilder = HttpClientBuilder.create(); // max total connections if (config.isSetMaxConnections()) { clientBuilder.setMaxConnTotal(config.getMaxConnections()); }//from w w w . ja va 2 s . co m // max connections per route if (config.isSetMaxConnectionsPerRoute()) { clientBuilder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute()); } RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH) .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true); // connection timeout if (config.isSetConnectionTimeout()) { requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout()); } // soucket timeout if (config.isSetSocketTimeout()) { requestConfigBuilder.setSocketTimeout(config.getSocketTimeout()); } // soucket timeout if (config.isSetFollowRedirects()) { requestConfigBuilder.setRedirectsEnabled(config.getFollowRedirects()); } clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build()); if (config.isSetUseRetry()) { if (config.getUseRetry()) { clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler()); } else { clientBuilder.setRetryHandler(NO_RETRY); } } // basic authentication if (config.isSetBasicAuthUsername() && config.isSetBasicAuthPassword()) { CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(config.getBasicAuthUsername(), config.getBasicAuthPassword())); } if (config.isSetAllowCompression()) { clientBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor()); clientBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor()); } // SSL context for secure connections can be created either based on // system or application specific properties. SSLContext sslcontext = SSLContexts.createSystemDefault(); // Use custom hostname verifier to customize SSL hostname verification. X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier(); // Create a registry of custom connection socket factories for supported // protocol schemes. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.INSTANCE) .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build(); clientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry)); return clientBuilder; }
From source file:nl.jk_5.nailed.plugin.nmm.NmmPlugin.java
@Subscribe public void registerMappacks(LoadMappacksEvent event) { HttpClient httpClient = HttpClientBuilder.create().build(); try {/*from w w w.jav a 2s. co m*/ HttpGet request = new HttpGet("http://nmm.jk-5.nl/mappacks.json"); HttpResponse response = httpClient.execute(request); MappacksList list = gson.fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), MappacksList.class); for (String mappack : list.mappacks) { event.register(new NmmMappack(mappack, this)); } this.logger.info("Registered " + list.mappacks.length + " nmm mappacks"); } catch (Exception e) { this.logger.warn("Was not able to fetch mappacks from nmm.jk-5.nl", e); } }
From source file:com.qdeve.oilprice.configuration.HttpConfiguration.java
private HttpClient httpclient() { HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties(); if (appPropertries.getProxyHost() != null && appPropertries.getProxyPort() != null) { builder.setProxy(new HttpHost(appPropertries.getProxyHost(), appPropertries.getProxyPort())); }/*from www . j a va 2s . c o m*/ return builder.build(); }
From source file:co.aurasphere.botmill.skype.util.network.NetworkUtils.java
/** * Send.// w w w . j a v a2 s.co m * * @param request the request * @return the string */ private static String send(HttpRequestBase request) { CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(null, null); provider.setCredentials(AuthScope.ANY, credentials); CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(provider).build(); logger.debug(request.getRequestLine().toString()); HttpResponse httpResponse = null; String response = null; try { httpResponse = httpClient.execute(request); response = logResponse(httpResponse); } catch (Exception e) { logger.error("Error during HTTP connection to Kik: ", e); } finally { try { httpClient.close(); } catch (IOException e) { logger.error("Error while closing HTTP connection: ", e); } } return response; }
From source file:com.graphaware.test.util.TestHttpClient.java
/** * Create a default client. */ public TestHttpClient() { this(HttpClientBuilder.create()); }
From source file:org.openmrs.module.webservices.rest.ITBase.java
@BeforeClass public static void waitForServerToStart() { synchronized (serverStartupLock) { if (!serverStarted) { final long time = System.currentTimeMillis(); final int timeout = 300000; final int retryAfter = 10000; final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(retryAfter) .setConnectTimeout(retryAfter).build(); final String startupUri = TEST_URL.getScheme() + "://" + TEST_URL.getHost() + ":" + TEST_URL.getPort() + TEST_URL.getPath(); System.out.println(//ww w. ja v a 2 s . c om "Waiting for server at " + startupUri + " for " + timeout / 1000 + " more seconds..."); while (System.currentTimeMillis() - time < timeout) { try { final HttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build(); final HttpGet sessionGet = new HttpGet(startupUri); sessionGet.setConfig(requestConfig); final HttpClientContext context = HttpClientContext.create(); final HttpResponse response = client.execute(sessionGet, context); int status = response.getStatusLine().getStatusCode(); if (status >= 400) { throw new RuntimeException(status + " " + response.getStatusLine().getReasonPhrase()); } URI finalUri = sessionGet.getURI(); List<URI> redirectLocations = context.getRedirectLocations(); if (redirectLocations != null) { finalUri = redirectLocations.get(redirectLocations.size() - 1); } String finalUriString = finalUri.toString(); if (!finalUriString.contains("initialsetup")) { serverStarted = true; return; } } catch (IOException e) { System.out.println(e.toString()); } try { System.out.println("Waiting for " + (timeout - (System.currentTimeMillis() - time)) / 1000 + " more seconds..."); Thread.sleep(retryAfter); } catch (InterruptedException e) { throw new RuntimeException(e); } } throw new RuntimeException("Server startup took longer than 5 minutes!"); } } }
From source file:de.unirostock.sems.cbarchive.web.HttpImporter.java
public HttpImporter(String remoteUrl, UserManager user) { this.remoteUrl = remoteUrl; this.user = user; this.client = HttpClientBuilder.create().build(); }
From source file:com.linecorp.armeria.server.thrift.ThriftOverHttp1Test.java
public ThriftOverHttp1Test() { try {/* w ww . j a va 2 s . c o m*/ SSLContext sslCtx = SSLContextBuilder.create() .loadTrustMaterial((TrustStrategy) (chain, authType) -> true).build(); httpClient = HttpClientBuilder.create().setSSLContext(sslCtx).build(); } catch (Exception e) { throw new Error(e); } }