List of usage examples for org.apache.http.impl.client HttpClients custom
public static HttpClientBuilder custom()
From source file:com.johnson.grab.browser.HttpClientHolder.java
private static void init() { // custom builder builder = HttpClients.custom(); PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(); manager.setDefaultMaxPerRoute(DEFAULT_MAX_NUM_PER_ROUTE); manager.setMaxTotal(DEFAULT_MAX_TOTAL_NUM); builder.setConnectionManager(manager); builder.setMaxConnPerRoute(DEFAULT_MAX_NUM_PER_ROUTE); builder.setMaxConnTotal(DEFAULT_MAX_TOTAL_NUM); // headers/*from ww w . j a v a 2 s . c o m*/ List<Header> headers = new ArrayList<Header>(); headers.add(new BasicHeader("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg," + " application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint," + " application/msword, */*")); headers.add(new BasicHeader("Accept-Language", "zh-cn,en-us,zh-tw,en-gb,en;")); headers.add(new BasicHeader("Accept-Charset", "gbk,gb2312,utf-8,BIG5,ISO-8859-1;")); headers.add(new BasicHeader("Connection", "Close")); headers.add(new BasicHeader("Cache-Control", "no-cache")); headers.add(new BasicHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; CIBA)")); headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch")); headers.add(new BasicHeader("Connection", "close")); builder.setDefaultHeaders(headers); // retry handler builder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAX_EXECUTION_NUM) { return false; } if (exception instanceof ConnectTimeoutException) { return false; } if (exception instanceof InterruptedIOException) { return false; } if (exception instanceof UnknownHostException) { return false; } if (exception instanceof NoHttpResponseException) { return false; } if (exception instanceof SSLException) { return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }); // build client client = builder.build(); }
From source file:org.springframework.cloud.stream.binder.rabbit.admin.RabbitManagementUtils.java
public static RestTemplate buildRestTemplate(String adminUri, String user, String password) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(user, password)); HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build(); // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT // Create AuthCache instance AuthCache authCache = new BasicAuthCache(); // Generate BASIC scheme object and add it to the local; from the apache docs... // auth cache BasicScheme basicAuth = new BasicScheme(); URI uri;//from w w w.ja va 2 s. c om try { uri = new URI(adminUri); } catch (URISyntaxException e) { throw new RabbitAdminException("Invalid URI", e); } authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth); // Add AuthCache to the execution context final HttpClientContext localContext = HttpClientContext.create(); localContext.setAuthCache(authCache); RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) { @Override protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) { return localContext; } }); restTemplate.setMessageConverters( Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter())); return restTemplate; }
From source file:io.kamax.mxisd.spring.CloseableHttpClientFactory.java
@Bean public CloseableHttpClient getClient() { return HttpClients.custom().setUserAgent("mxisd").setMaxConnPerRoute(Integer.MAX_VALUE) .setMaxConnTotal(Integer.MAX_VALUE).build(); }
From source file:com.esri.geoportal.harvester.beans.GeometryServiceBean.java
/** * Creates instance of the bean./* w w w .ja v a 2s . co m*/ * @param geometryServiceUrl geometry service url. * @throws MalformedURLException if invalid geometry service url */ public GeometryServiceBean(String geometryServiceUrl) throws MalformedURLException { super(HttpClients.custom().useSystemProperties().build(), new URL(geometryServiceUrl)); }
From source file:org.neo4j.ogm.drivers.http.driver.HttpDriverTest.java
@Test @Ignore/* www . j a v a2s .co m*/ public void shouldInitialiseWithCustomHttpClient() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(1); connectionManager.setDefaultMaxPerRoute(1); CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build(); // TODO does this still have any value? // DriverManager.register(new HttpDriver(httpClient)); // assertThat(DriverManager.getDriver()).isNotNull(); }
From source file:com.supermap.desktop.icloud.impl.LicenseServiceFactory.java
public static CloseableHttpClient getClient(String username, String password) { CloseableHttpClient client = null;//ww w.j a v a 2 s. co m AuthenticatorImpl authenticator = new AuthenticatorImpl(); authenticator.setSsoHttpClientBuilder(HttpClients.custom()); try { client = authenticator.authenticate(new UsernamePassword(username, password), HttpClients.custom(), LICENSE_SERVICE_LOGIN); } catch (AuthenticationException e) { e.printStackTrace(); } return client; }
From source file:com.granita.icloudcalsync.webdav.DavHttpClient.java
@SuppressLint("LogTagMismatch") public static CloseableHttpClient create() { PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager( socketFactoryRegistry);/* ww w . j a va 2 s. c o m*/ // limits per DavHttpClient (= per DavSyncAdapter extends AbstractThreadedSyncAdapter) connectionManager.setMaxTotal(3); // max. 3 connections in total connectionManager.setDefaultMaxPerRoute(2); // max. 2 connections per host HttpClientBuilder builder = HttpClients.custom().useSystemProperties() .setConnectionManager(connectionManager).setDefaultRequestConfig(defaultRqConfig) .setRetryHandler(DavHttpRequestRetryHandler.INSTANCE) .setRedirectStrategy(DavRedirectStrategy.INSTANCE) .setUserAgent("DAVdroid/" + Constants.APP_VERSION); if (Log.isLoggable("Wire", Log.DEBUG)) { Log.i(TAG, "Wire logging active, disabling HTTP compression"); builder = builder.disableContentCompression(); } return builder.build(); }
From source file:com.afrisoftech.lib.PDF2ExcelConverter.java
public static void convertPDf2Excel(String pdfFile2Convert) throws Exception { if (pdfFile2Convert.length() < 3) { System.out.println("File to convert is mandatory!"); javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!"); } else {// w ww. j av a 2 s. c o m final String apiKey = "ktxpfvf0i5se"; final String format = "xlsx-single".toLowerCase(); final String pdfFilename = pdfFile2Convert; if (!formats.contains(format)) { System.out.println("Invalid output format: \"" + format + "\""); } // Avoid cookie warning with default cookie configuration RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build(); File inputFile = new File(pdfFilename); if (!inputFile.canRead()) { System.out.println("Can't read input PDF file: \"" + pdfFilename + "\""); javax.swing.JOptionPane.showMessageDialog(null, "File to convert is mandatory!"); } try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .build()) { HttpPost httppost = new HttpPost("https://pdftables.com/api?format=" + format + "&key=" + apiKey); FileBody fileBody = new FileBody(inputFile); HttpEntity requestBody = MultipartEntityBuilder.create().addPart("f", fileBody).build(); httppost.setEntity(requestBody); System.out.println("Sending request"); try (CloseableHttpResponse response = httpclient.execute(httppost)) { if (response.getStatusLine().getStatusCode() != 200) { System.out.println(response.getStatusLine()); javax.swing.JOptionPane.showMessageDialog(null, "Internet connection is a must. Consult IT administrator for further assistance"); } HttpEntity resEntity = response.getEntity(); if (resEntity != null) { final String outputFilename = getOutputFilename(pdfFilename, format.replaceFirst("-.*$", "")); System.out.println("Writing output to " + outputFilename); final File outputFile = new File(outputFilename); FileUtils.copyInputStreamToFile(resEntity.getContent(), outputFile); if (java.awt.Desktop.isDesktopSupported()) { try { java.awt.Desktop.getDesktop().open(outputFile); } catch (IOException ex) { javax.swing.JOptionPane.showMessageDialog(new java.awt.Frame(), ex.getMessage()); ex.printStackTrace(); //Exceptions.printStackTrace(ex); } } } else { System.out.println("Error: file missing from response"); javax.swing.JOptionPane.showMessageDialog(null, "Error: file missing from response! Internet connection is a must."); } } } } }
From source file:com.lixiaocong.util.weather.WeatherHelper.java
public static Weather getWeather(String city) throws IOException { HttpClient httpClient = HttpClients.custom().build(); HttpGet httpGet = new HttpGet("http://apis.baidu.com/apistore/weatherservice/weather?citypinyin=" + city); httpGet.addHeader("apikey", "f6e1b7c306d087df20761632655bc18b"); RequestConfig config = RequestConfig.custom().setConnectTimeout(500).build(); httpGet.setConfig(config);//from w w w. j av a 2 s .com HttpResponse response = httpClient.execute(httpGet); String jsonString = EntityUtils.toString(response.getEntity()); logger.info("weather server returns " + jsonString); ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(jsonString, Weather.class); }
From source file:network.ProxiedHttpClientAdaptor.java
public ProxiedHttpClientAdaptor(HttpHost proxy, String encode) { super(encode); DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy); this.httpclient = HttpClients.custom().setRoutePlanner(routePlanner).build(); }