Example usage for org.apache.http.impl.client HttpClientBuilder setRetryHandler

List of usage examples for org.apache.http.impl.client HttpClientBuilder setRetryHandler

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setRetryHandler.

Prototype

public final HttpClientBuilder setRetryHandler(final HttpRequestRetryHandler retryHandler) 

Source Link

Document

Assigns HttpRequestRetryHandler instance.

Usage

From source file:org.wso2.security.tools.product.manager.handler.HttpRequestHandler.java

/**
 * Send HTTP GET request/*from   w  ww  .jav a  2s .  c  o  m*/
 *
 * @param request Requested URI
 * @return HTTPResponse after executing the command
 */
public static HttpResponse sendGetRequest(URI request) {
    try {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        HttpClient httpClient = clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
                .build();
        HttpGet httpGetRequest = new HttpGet(request);
        return httpClient.execute(httpGetRequest);
    } catch (IOException e) {
        LOGGER.error("Error occurred while sending GET request to " + request.getPath(), e);
    }
    return null;
}

From source file:org.wso2.security.tools.product.manager.handler.HttpRequestHandler.java

/**
 * Send HTTP POST request/*from  w  ww .  j ava 2 s .c o  m*/
 *
 * @param requestURI Requested URI
 * @return HTTPResponse after executing the command
 */
public static HttpResponse sendPostRequest(String requestURI, ArrayList<NameValuePair> parameters) {
    try {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        HttpClient httpClient = clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
                .build();
        HttpPost httpPostRequest = new HttpPost(requestURI);

        for (NameValuePair parameter : parameters) {
            urlParameters.add(new BasicNameValuePair(parameter.getName(), parameter.getValue()));
        }

        httpPostRequest.setEntity(new UrlEncodedFormEntity(urlParameters));
        return httpClient.execute(httpPostRequest);
    } catch (IOException e) {
        LOGGER.error("Error occurred while sending POST request to " + requestURI, e);
    }
    return null;
}

From source file:ninja.siden.internal.Testing.java

static CloseableHttpClient client() {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(200).build());
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return builder.build();
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestConnectionSelectingSSLSocketFactoryIntegrationTest.java

private static void createClient() throws Exception {
    RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create();

    socketFactoryRegistry.register("http", PlainConnectionSocketFactory.INSTANCE);

    socketFactoryRegistry.register("https", createSSLSocketFactory());

    PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry.build());
    connMgr.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connMgr.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from  ww  w  .j  a  va2  s. c o m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(timeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(connMgr);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java

/**
 * Creates HTTP client./*w w w  . j  a  v a 2 s  .  c om*/
 * @param authKey the client's authentication key
 * @param clientMaxTotalConnections client max total connections
 * @param clientMaxConnectionsPerRoute client max connections per route
 * @param connectionTimeoutMilliseconds connection timeout in milliseconds
 * @param socketTimeoutMilliseconds socket timeout in milliseconds
 * @return HTTP client
 * @throws Exception if creating a HTTPS client and SSLContext
 * initialization fails
 */
public static CloseableHttpClient createHttpClient(InternalSSLKey authKey, int clientMaxTotalConnections,
        int clientMaxConnectionsPerRoute, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds)
        throws Exception {
    log.trace("createHttpClient()");

    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    if ("https".equalsIgnoreCase(OpMonitoringSystemProperties.getOpMonitorDaemonScheme())) {
        sfr.register("https", createSSLSocketFactory(authKey));
    } else {
        sfr.register("http", PlainConnectionSocketFactory.INSTANCE);
    }

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(clientMaxTotalConnections);
    cm.setDefaultMaxPerRoute(clientMaxConnectionsPerRoute);
    cm.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());

    RequestConfig.Builder rb = RequestConfig.custom().setConnectTimeout(connectionTimeoutMilliseconds)
            .setConnectionRequestTimeout(connectionTimeoutMilliseconds)
            .setSocketTimeout(socketTimeoutMilliseconds);

    HttpClientBuilder cb = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from www .ja  v a 2s. c  om
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

From source file:org.apache.solr.client.solrj.impl.HttpClientUtil.java

private static HttpClientBuilder setupBuilder(HttpClientBuilder builder, SolrParams config) {

    Builder requestConfigBuilder = RequestConfig.custom()
            .setRedirectsEnabled(config.getBool(HttpClientUtil.PROP_FOLLOW_REDIRECTS, false))
            .setDecompressionEnabled(false)
            .setConnectTimeout(config.getInt(HttpClientUtil.PROP_CONNECTION_TIMEOUT, DEFAULT_CONNECT_TIMEOUT))
            .setSocketTimeout(config.getInt(HttpClientUtil.PROP_SO_TIMEOUT, DEFAULT_SO_TIMEOUT));

    String cpolicy = cookiePolicy;
    if (cpolicy != null) {
        requestConfigBuilder.setCookieSpec(cpolicy);
    }//  w w  w. j av  a 2s.  com

    RequestConfig requestConfig = requestConfigBuilder.build();

    HttpClientBuilder retBuilder = builder.setDefaultRequestConfig(requestConfig);

    if (config.getBool(HttpClientUtil.PROP_USE_RETRY, true)) {
        retBuilder = retBuilder.setRetryHandler(new SolrHttpRequestRetryHandler(3));

    } else {
        retBuilder = retBuilder.setRetryHandler(NO_RETRY);
    }

    final String basicAuthUser = config.get(HttpClientUtil.PROP_BASIC_AUTH_USER);
    final String basicAuthPass = config.get(HttpClientUtil.PROP_BASIC_AUTH_PASS);

    if (basicAuthUser != null && basicAuthPass != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(basicAuthUser, basicAuthPass));
        retBuilder.setDefaultCredentialsProvider(credsProvider);
    }

    if (config.getBool(HttpClientUtil.PROP_ALLOW_COMPRESSION, false)) {
        retBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        retBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    } else {
        retBuilder.disableContentCompression();
    }

    return retBuilder;
}

From source file:com.teradata.tempto.internal.hadoop.hdfs.HdfsModuleProvider.java

@Override
public Module getModule(Configuration configuration) {
    return new PrivateModule() {
        @Override//from w  w w.  j  a  v  a 2 s. c om
        protected void configure() {
            install(httpRequestsExecutorModule());

            bind(HdfsClient.class).to(WebHdfsClient.class).in(Scopes.SINGLETON);
            bind(RevisionStorage.class).toProvider(RevisionStorageProvider.class).in(Scopes.SINGLETON);
            bind(HdfsDataSourceWriter.class).to(DefaultHdfsDataSourceWriter.class).in(Scopes.SINGLETON);

            expose(HdfsClient.class);
            expose(RevisionStorage.class);
            expose(HdfsDataSourceWriter.class);
        }

        private Module httpRequestsExecutorModule() {
            if (spnegoAuthenticationRequired()) {
                return new SpnegoHttpRequestsExecutor.Module();
            } else {
                return new SimpleHttpRequestsExecutor.Module();
            }
        }

        private boolean spnegoAuthenticationRequired() {
            Optional<String> authentication = configuration.getString("hdfs.webhdfs.authentication");
            return authentication.isPresent() && authentication.get().equalsIgnoreCase(AUTHENTICATION_SPNEGO);
        }

        @Inject
        @Provides
        @Singleton
        CloseableHttpClient createHttpClient() {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(NUMBER_OF_HTTP_RETRIES, true));
            return httpClientBuilder.build();
        }
    };
}

From source file:com.miapc.ipudong.Application.java

@Bean
public RestTemplate getRestTemplate() {
    SSLContext sslcontext = null;
    Set<KeyManager> keymanagers = new LinkedHashSet<>();
    Set<TrustManager> trustmanagers = new LinkedHashSet<>();
    try {//from w  w  w  . ja  va  2  s .  co  m
        trustmanagers.add(new HttpsTrustManager());
        KeyManager[] km = keymanagers.toArray(new KeyManager[keymanagers.size()]);
        TrustManager[] tm = trustmanagers.toArray(new TrustManager[trustmanagers.size()]);
        sslcontext = SSLContexts.custom().build();
        sslcontext.init(km, tm, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setSSLSocketFactory(factory);
    // ?3?
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(2, true));
    // ????Keep-Alive
    httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());

    List<Header> headers = new ArrayList<>();
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
    headers.add(new BasicHeader("Accept-Language", "zh-CN"));
    headers.add(new BasicHeader("Connection", "Keep-Alive"));
    headers.add(new BasicHeader("Authorization", "reslibu"));
    httpClientBuilder.setDefaultHeaders(headers);
    CloseableHttpClient httpClient = httpClientBuilder.build();
    if (httpClient != null) {
        // httpClient??RequestConfig
        HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
                httpClient);
        // 
        clientHttpRequestFactory.setConnectTimeout(60 * 1000);
        // ???SocketTimeout
        clientHttpRequestFactory.setReadTimeout(5 * 60 * 1000);
        // ????
        clientHttpRequestFactory.setConnectionRequestTimeout(5000);
        // ?truePOSTPUT????false?
        // clientHttpRequestFactory.setBufferRequestBody(false);
        // ?
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new MappingJackson2XmlHttpMessageConverter());

        RestTemplate restTemplate = new RestTemplate(messageConverters);
        restTemplate.setRequestFactory(clientHttpRequestFactory);
        restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
        return restTemplate;
    } else {
        return null;
    }

}

From source file:ee.ria.xroad.proxy.serverproxy.HttpClientCreator.java

private void build() throws HttpClientCreatorException {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.create();
    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    try {//  w w w.jav  a  2 s  .c om
        sfr.register("https", createSSLSocketFactory());
    } catch (Exception e) {
        throw new HttpClientCreatorException("Creating SSL Socket Factory failed", e);
    }

    connectionManager = new PoolingHttpClientConnectionManager(sfr.build());
    connectionManager.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);
    connectionManager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(CLIENT_TIMEOUT);
    rb.setConnectionRequestTimeout(CLIENT_TIMEOUT);
    rb.setSocketTimeout(CLIENT_TIMEOUT);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setDefaultRequestConfig(rb.build());
    cb.setConnectionManager(connectionManager);

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    httpClient = cb.build();
}