org.apache.http.impl.nio.client.HttpAsyncClients Java Examples

The following examples show how to use org.apache.http.impl.nio.client.HttpAsyncClients. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: YunpianClient.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
private CloseableHttpAsyncClient createHttpAsyncClient(YunpianConf conf) throws IOReactorException {
    IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setIoThreadCount(Runtime.getRuntime().availableProcessors())
            .setConnectTimeout(conf.getConfInt(YunpianConf.HTTP_CONN_TIMEOUT, "10000"))
            .setSoTimeout(conf.getConfInt(YunpianConf.HTTP_SO_TIMEOUT, "30000")).build();
    ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);

    PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(ioReactor);
    ConnectionConfig connectionConfig = ConnectionConfig.custom().setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .setCharset(Charset.forName(conf.getConf(YunpianConf.HTTP_CHARSET, YunpianConf.HTTP_CHARSET_DEFAULT))).build();
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setMaxTotal(conf.getConfInt(YunpianConf.HTTP_CONN_MAXTOTAL, "100"));
    connManager.setDefaultMaxPerRoute(conf.getConfInt(YunpianConf.HTTP_CONN_MAXPERROUTE, "10"));

    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setConnectionManager(connManager).build();
    httpclient.start();
    return httpclient;
}
 
Example #2
Source File: AsyncClientPipelinedStreaming.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining();
    try {
        httpclient.start();

        HttpHost targetHost = new HttpHost("localhost", 8080);
        HttpGet[] resquests = { new HttpGet("/docs/index.html"), new HttpGet("/docs/introduction.html"),
                new HttpGet("/docs/setup.html"), new HttpGet("/docs/config/index.html") };

        List<MyRequestProducer> requestProducers = new ArrayList<MyRequestProducer>();
        List<MyResponseConsumer> responseConsumers = new ArrayList<MyResponseConsumer>();
        for (HttpGet request : resquests) {
            requestProducers.add(new MyRequestProducer(targetHost, request));
            responseConsumers.add(new MyResponseConsumer(request));
        }

        Future<List<Boolean>> future = httpclient.execute(targetHost, requestProducers, responseConsumers, null);
        future.get();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example #3
Source File: AsyncClientProxyAuthentication.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("someproxy", 8080),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet("https://issues.apache.org/");
        httpget.setConfig(config);
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example #4
Source File: ConnectorCommon.java    From nextcloud-java-api with GNU General Public License v3.0 6 votes vote down vote up
public static CloseableHttpAsyncClient getInstance(ServerConfig serverConfig)
	throws IOException{
	if (HTTPC_CLIENT == null) {
		if (serverConfig.isTrustAllCertificates()) {
			try {
				SSLContext sslContext = SSLContexts.custom()
					.loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
				HTTPC_CLIENT = HttpAsyncClients.custom()
					.setSSLHostnameVerifier((NoopHostnameVerifier.INSTANCE))
					.setSSLContext(sslContext)
					.build();
			} catch (KeyManagementException | NoSuchAlgorithmException
					| KeyStoreException e) {
				throw new IOException(e);
			} 
			
		} else {
			HTTPC_CLIENT = HttpAsyncClients.createDefault();
		}
		
		HTTPC_CLIENT.start();
	}
	return HTTPC_CLIENT;
}
 
Example #5
Source File: AsyncClientAuthentication.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 443),
            new UsernamePasswordCredentials("username", "password"));
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build();
    try {
        HttpGet httpget = new HttpGet("http://localhost/");

        System.out.println("Executing request " + httpget.getRequestLine());
        Future<HttpResponse> future = httpclient.execute(httpget, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example #6
Source File: AsyncClientPipelined.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpPipeliningClient httpclient = HttpAsyncClients.createPipelining();
    try {
        httpclient.start();

        HttpHost targetHost = new HttpHost("localhost", 8080);
        HttpGet[] resquests = { new HttpGet("/docs/index.html"), new HttpGet("/docs/introduction.html"),
                new HttpGet("/docs/setup.html"), new HttpGet("/docs/config/index.html") };

        Future<List<HttpResponse>> future = httpclient.execute(targetHost, Arrays.<HttpRequest>asList(resquests),
                null);
        List<HttpResponse> responses = future.get();
        System.out.println(responses);

        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example #7
Source File: AsyncClientHttpExchangeStreaming.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        Future<Boolean> future = httpclient.execute(HttpAsyncMethods.createGet("http://localhost:8080/"),
                new MyResponseConsumer(), null);
        Boolean result = future.get();
        if (result != null && result.booleanValue()) {
            System.out.println("Request successfully executed");
        } else {
            System.out.println("Request failed");
        }
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example #8
Source File: AsyncClientExecuteProxy.java    From yunpian-java-sdk with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        HttpHost proxy = new HttpHost("someproxy", 8080);
        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        request.setConfig(config);
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
}
 
Example #9
Source File: ODataProductSynchronizer.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
           new UsernamePasswordCredentials(serviceUser, servicePass));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
 
Example #10
Source File: HttpAsyncClientLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void whenUseCookiesWithHttpAsyncClient_thenCorrect() throws Exception {
    final BasicCookieStore cookieStore = new BasicCookieStore();
    final BasicClientCookie cookie = new BasicClientCookie(COOKIE_NAME, "1234");
    cookie.setDomain(COOKIE_DOMAIN);
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    final CloseableHttpAsyncClient client = HttpAsyncClients.custom().build();
    client.start();
    final HttpGet request = new HttpGet(HOST_WITH_COOKIE);

    final HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);

    final Future<HttpResponse> future = client.execute(request, localContext, null);
    final HttpResponse response = future.get();
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
    client.close();
}
 
Example #11
Source File: HttpProxyClient.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private CloseableHttpAsyncClient getAsyncProxyHttpClient(URI proxyUri) {
  LOG.info("Creating async proxy http client");
  PoolingNHttpClientConnectionManager cm = getAsyncConnectionManager();
  HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort());
  
  HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom();
  if (cm != null) {
    clientBuilder = clientBuilder.setConnectionManager(cm);
  }

  if (proxy != null) {
    clientBuilder = clientBuilder.setProxy(proxy);
  }
  clientBuilder = setRedirects(clientBuilder);
  return clientBuilder.build();
}
 
Example #12
Source File: SaltService.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Default constructor
 */
public SaltService() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(0)
            .setSocketTimeout(0)
            .setConnectionRequestTimeout(0)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    asyncHttpClient = httpClientBuilder
            .setMaxConnPerRoute(20)
            .setMaxConnTotal(20)
            .build();
    asyncHttpClient.start();

    SALT_CLIENT = new SaltClient(SALT_MASTER_URI, new HttpAsyncClientImpl(asyncHttpClient));
    saltSSHService = new SaltSSHService(SALT_CLIENT, SaltActionChainGeneratorService.INSTANCE);
    defaultBatch = Batch.custom().withBatchAsAmount(ConfigDefaults.get().getSaltBatchSize())
                    .withDelay(ConfigDefaults.get().getSaltBatchDelay())
                    .withPresencePingTimeout(ConfigDefaults.get().getSaltPresencePingTimeout())
                    .withPresencePingGatherJobTimeout(ConfigDefaults.get().getSaltPresencePingGatherJobTimeout())
                    .build();
}
 
Example #13
Source File: ODataClient.java    From DataHubSystem with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableHttpAsyncClient generateClient ()
{
   CredentialsProvider credsProvider = new BasicCredentialsProvider();
   credsProvider.setCredentials(new AuthScope (AuthScope.ANY),
            new UsernamePasswordCredentials(username, password));
   RequestConfig rqconf = RequestConfig.custom()
         .setCookieSpec(CookieSpecs.DEFAULT)
         .setSocketTimeout(Timeouts.SOCKET_TIMEOUT)
         .setConnectTimeout(Timeouts.CONNECTION_TIMEOUT)
         .setConnectionRequestTimeout(Timeouts.CONNECTION_REQUEST_TIMEOUT)
         .build();
   CloseableHttpAsyncClient res = HttpAsyncClients.custom ()
         .setDefaultCredentialsProvider (credsProvider)
         .setDefaultRequestConfig(rqconf)
         .build ();
   res.start ();
   return res;
}
 
Example #14
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpPost httpPost = new HttpPost("/hello4");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpHost, httpPost, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example #15
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpHost httpHost = new HttpHost("localhost", getPort());
    HttpGet httpGet = new HttpGet("/hello2");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpHost, httpGet, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example #16
Source File: BufferedJestClientFactory.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
protected CloseableHttpAsyncClient createAsyncHttpClient(NHttpClientConnectionManager connectionManager) {
    return HttpAsyncClients.custom()
                    .setConnectionManager(connectionManager)
                    .setDefaultRequestConfig(getRequestConfig())
                    .setProxyAuthenticationStrategy(wrappedHttpClientConfig.getHttpClientConfig().getProxyAuthenticationStrategy())
                    .setRoutePlanner(getRoutePlanner())
                    .setDefaultCredentialsProvider(wrappedHttpClientConfig.getHttpClientConfig().getCredentialsProvider())
    .build();
}
 
Example #17
Source File: TestUtils.java    From salt-netapi-client with MIT License 5 votes vote down vote up
public static CloseableHttpAsyncClient defaultClient() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(0)
            .setConnectTimeout(0)
            .setSocketTimeout(0)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();
    return asyncHttpClient;
}
 
Example #18
Source File: BalancerConfiguration.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and configures HttpProxy
 */
@Bean
HttpProxy httpProxy() {
    ProxyClient proxyClient;
    if (async) {
        if (metricsEbanled) {
            //Building HTTP Async client wrapper for gathering metrics
            proxyClient = new AsyncProxyClient(configuredHttpAsyncClient(new InstrumentedNHttpClientBuilder(metricRegistry, QUERYLESS_URL)));
            LOG.info("metrics enabled");
        } else {
            //Building Default HTTP Async client
            LOG.warn("metrics disabled");
            proxyClient = new AsyncProxyClient(configuredHttpAsyncClient(HttpAsyncClients.custom()));
        }
    } else {
        if (metricsEbanled) {
            //Building HTTP sync client wrapper for gathering metrics
            proxyClient = new SyncProxyClient(configuredHttpClient(InstrumentedHttpClients.custom(metricRegistry, QUERYLESS_URL)));
            LOG.info("metrics enabled");
        } else {
            //Building Default HTTP sync client
            LOG.warn("metrics disabled");
            proxyClient = new SyncProxyClient(configuredHttpClient(HttpClients.custom()));
        }
    }
    return proxyInstance = new HttpProxy(proxyClient);
}
 
Example #19
Source File: InterruptibleHttpClient.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
/** An InterruptibleHttpClient usign {@code HttpAsyncClients.createDefault()}
 * as HttpAsyncClientProducer. */
public InterruptibleHttpClient ()
{
   clientProducer = new HttpAsyncClientProducer ()
   {
      @Override
      public CloseableHttpAsyncClient generateClient ()
      {
         CloseableHttpAsyncClient res = HttpAsyncClients.createDefault ();
         res.start ();
         return res;
      }
   };
}
 
Example #20
Source File: ApacheAsyncClientExecutor.java    From Thunder with Apache License 2.0 5 votes vote down vote up
public void initialize(final ThunderProperties properties) throws Exception {
    final CyclicBarrier barrier = new CyclicBarrier(2);
    Executors.newCachedThreadPool().submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            try {
                IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
                        .setIoThreadCount(ThunderConstant.CPUS)
                        .setConnectTimeout(properties.getInteger(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME))
                        .setSoTimeout(properties.getInteger(ThunderConstant.APACHE_SO_TIMEOUT_ATTRIBUTE_NAME))
                        .setSndBufSize(properties.getInteger(ThunderConstant.APACHE_SNDBUF_SIZE_ATTRIBUTE_NAME))
                        .setRcvBufSize(properties.getInteger(ThunderConstant.APACHE_RCVBUF_SIZE_ATTRIBUTE_NAME))
                        .setBacklogSize(properties.getInteger(ThunderConstant.APACHE_BACKLOG_SIZE_ATTRIBUTE_NAME))
                        .setTcpNoDelay(true)
                        .setSoReuseAddress(true)
                        .setSoKeepAlive(true)
                        .build();
                ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
                PoolingNHttpClientConnectionManager httpManager = new PoolingNHttpClientConnectionManager(ioReactor);
                httpManager.setMaxTotal(ThunderConstant.CPUS * properties.getInteger(ThunderConstant.APACHE_MAX_TOTAL_ATTRIBUTE_NAME));

                httpAsyncClient = HttpAsyncClients.custom().setConnectionManager(httpManager).build();
                httpAsyncClient.start();

                LOG.info("Create apache async client successfully");

                barrier.await();
            } catch (IOReactorException e) {
                LOG.error("Create apache async client failed", e);
            }

            return null;
        }
    });

    barrier.await(properties.getLong(ThunderConstant.APACHE_CONNECT_TIMEOUT_ATTRIBUTE_NAME) * 2, TimeUnit.MILLISECONDS);
}
 
Example #21
Source File: ImportRunner.java    From newts with Apache License 2.0 5 votes vote down vote up
private Observable<Boolean> restPoster(Observable<List<Sample>> samples,  MetricRegistry metrics) {

        final CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
        httpClient.start();


        return samples

                // turn each batch into json
                .map(toJSON())

                // meter them as the go into the post code
                .map(meter(metrics.meter("posts"), String.class))

                // post the json to the REST server
                .mergeMap(postJSON(m_restUrl, httpClient))

                // meter the responses
                .map(meter(metrics.meter("responses"), ObservableHttpResponse.class))
                
                // count sample completions
                .map(meter(metrics.meter("samples-completed"), m_samplesPerBatch, ObservableHttpResponse.class))

                // make sure every request has a successful return code
                .all(successful())
                
                .doOnCompleted(new Action0() {

                    @Override
                    public void call() {
                        try {
                            httpClient.close();
                        } catch (IOException e) {
                            System.err.println("Failed to close httpClient!");
                            e.printStackTrace();
                        }
                    }
                    
                });
    }
 
Example #22
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpGet httpGet = new HttpGet("http://localhost:" + getPort() + "/hello1");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpGet, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example #23
Source File: ApacheHttpAsyncClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
    httpClient.start();
    HttpPost httpPost = new HttpPost("http://localhost:" + getPort() + "/hello3");
    SimpleFutureCallback callback = new SimpleFutureCallback();
    Future<HttpResponse> future = httpClient.execute(httpPost, callback);
    callback.latch.await();
    httpClient.close();
    int responseStatusCode = future.get().getStatusLine().getStatusCode();
    if (responseStatusCode != 200) {
        throw new IllegalStateException(
                "Unexpected response status code: " + responseStatusCode);
    }
}
 
Example #24
Source File: HttpFactory.java    From aliyun-tablestore-java-sdk with Apache License 2.0 5 votes vote down vote up
public static CloseableHttpAsyncClient createHttpAsyncClient(
        ClientConfiguration config, PoolingNHttpClientConnectionManager cm) {
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setConnectionManager(cm);
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(config.getConnectionTimeoutInMillisecond())
            .setSocketTimeout(config.getSocketTimeoutInMillisecond()).build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setUserAgent(Constants.USER_AGENT);
    httpClientBuilder.disableCookieManagement();

    String proxyHost = config.getProxyHost();
    int proxyPort = config.getProxyPort();
    if (proxyHost != null) {
        if (proxyPort <= 0) {
            throw new ClientException("The proxy port is invalid. Please check your configuration.");
        }
        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        httpClientBuilder.setProxy(proxy);
        String proxyUsername = config.getProxyUsername();
        String proxyPassword = config.getProxyPassword();
        if (proxyUsername != null && proxyPassword != null) {
            String proxyDomain = config.getProxyDomain();
            String proxyWorkstation = config.getProxyWorkstation();
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(proxyHost, proxyPort),
                new NTCredentials(
                    proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        }
    }

    return httpClientBuilder.build();
}
 
Example #25
Source File: HttpClientUtils.java    From salt-netapi-client with MIT License 5 votes vote down vote up
/**
 * Creates a simple default http client
 * @return HttpAsyncClient
 */
public static CloseableHttpAsyncClient defaultClient() {
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(0)
            .setConnectTimeout(10000)
            .setSocketTimeout(20000)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();
    return asyncHttpClient;
}
 
Example #26
Source File: AsyncClientCustomContext.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
	CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
	try {
		// Create a local instance of cookie store
		CookieStore cookieStore = new BasicCookieStore();

		// Create local HTTP context
		HttpClientContext localContext = HttpClientContext.create();
		// Bind custom cookie store to the local context
		localContext.setCookieStore(cookieStore);

           HttpGet httpget = new HttpGet("http://localhost/");
		System.out.println("Executing request " + httpget.getRequestLine());

		httpclient.start();

		// Pass local context as a parameter
		Future<HttpResponse> future = httpclient.execute(httpget, localContext, null);

		// Please note that it may be unsafe to access HttpContext instance
		// while the request is still being executed

		HttpResponse response = future.get();
		System.out.println("Response: " + response.getStatusLine());
		List<Cookie> cookies = cookieStore.getCookies();
		for (int i = 0; i < cookies.size(); i++) {
			System.out.println("Local cookie: " + cookies.get(i));
		}
		System.out.println("Shutting down");
	} finally {
		httpclient.close();
	}
}
 
Example #27
Source File: AsyncClientHttpExchange.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("http://www.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example #28
Source File: ZeroCopyHttpExchange.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
    try {
        httpclient.start();
        File upload = new File(args[0]);
        File download = new File(args[1]);
        ZeroCopyPost httpost = new ZeroCopyPost("http://localhost:8080/", upload, ContentType.create("text/plain"));
        ZeroCopyConsumer<File> consumer = new ZeroCopyConsumer<File>(download) {

            @Override
            protected File process(final HttpResponse response, final File file, final ContentType contentType)
                    throws Exception {
                if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                    throw new ClientProtocolException("Upload failed: " + response.getStatusLine());
                }
                return file;
            }

        };
        Future<File> future = httpclient.execute(httpost, consumer, null);
        File result = future.get();
        System.out.println("Response file length: " + result.length());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example #29
Source File: SaltClientTest.java    From salt-netapi-client with MIT License 5 votes vote down vote up
@Test
public void testRunRequestWithSocketTimeout() {
    exception.expect(CompletionException.class);
    exception.expectCause(instanceOf(SocketTimeoutException.class));

    RequestConfig requestConfig = RequestConfig.custom()
            .setSocketTimeout(1000)
            .setCookieSpec(CookieSpecs.STANDARD)
            .build();
    HttpAsyncClientBuilder httpClientBuilder = HttpAsyncClients.custom();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);

    CloseableHttpAsyncClient asyncHttpClient = httpClientBuilder.build();
    asyncHttpClient.start();

    // create a local SaltClient with a fast timeout configuration
    // to do not lock tests more than 2s
    URI uri = URI.create("http://localhost:" + Integer.toString(MOCK_HTTP_PORT));
    SaltClient clientWithFastTimeout = new SaltClient(uri, new HttpAsyncClientImpl(asyncHttpClient));


    stubFor(any(urlMatching(".*"))
            .willReturn(aResponse()
            .withFixedDelay(2000)));

    clientWithFastTimeout.login("user", "pass", AUTO).toCompletableFuture().join();
}
 
Example #30
Source File: AsyncClientHttpExchangeFutureCallback.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).build();
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig).build();
    try {
        httpclient.start();
        final HttpGet[] requests = new HttpGet[] { new HttpGet("http://www.apache.org/"),
                new HttpGet("https://www.verisign.com/"), new HttpGet("http://www.google.com/") };
        final CountDownLatch latch = new CountDownLatch(requests.length);
        for (final HttpGet request : requests) {
            httpclient.execute(request, new FutureCallback<HttpResponse>() {

                @Override
                public void completed(final HttpResponse response) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + response.getStatusLine());
                }

                @Override
                public void failed(final Exception ex) {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + "->" + ex);
                }

                @Override
                public void cancelled() {
                    latch.countDown();
                    System.out.println(request.getRequestLine() + " cancelled");
                }

            });
        }
        latch.await();
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}