org.apache.http.impl.client.DefaultHttpRequestRetryHandler Java Examples

The following examples show how to use org.apache.http.impl.client.DefaultHttpRequestRetryHandler. 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: MPRestClient.java    From dx-java with MIT License 10 votes vote down vote up
/**
 * Create a HttpClient
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(MercadoPago.SDK.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(), false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy())
            .setRetryHandler(retryHandler)
            .disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example #2
Source File: HttpPoolClient.java    From seezoon-framework-all with Apache License 2.0 6 votes vote down vote up
private CloseableHttpClient createHttpClient(HttpClientConnectionManager connectionManager) {
	//HttpHost proxy = new HttpHost("127.0.0.1",8889);
	RequestConfig requestConfig = RequestConfig.custom()
			//.setProxy(proxy)
			.setConnectionRequestTimeout(httpClientConfig.getConnectionRequestTimeout())// 获取连接等待时间
			.setConnectTimeout(httpClientConfig.getConnectTimeout())// 连接超时
			.setSocketTimeout(httpClientConfig.getSocketTimeout())// 获取数据超时
			.build();
	httpClient = HttpClients.custom().setConnectionManager(httpClientConnectionManager)
			.setDefaultRequestConfig(requestConfig)
			.setUserAgent(httpClientConfig.getUserAgent())
			.disableContentCompression().disableAutomaticRetries()
			.setConnectionTimeToLive(httpClientConfig.getConnTimeToLive(), TimeUnit.MILLISECONDS)// 连接最大存活时间
			.setRetryHandler(new DefaultHttpRequestRetryHandler(httpClientConfig.getRetyTimes(), true))// 重试次数
			.build();
	return httpClient;
}
 
Example #3
Source File: HttpClientPerformanceTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Before
public void initializeClient() {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(Math.max(1, MAX_THREADS / 10));
    connectionManager.setDefaultMaxPerRoute(connectionManager.getMaxTotal());
    connectionManager.setValidateAfterInactivity(10000);
    connectionManager.setDefaultSocketConfig(getDefaultSocketConfig());

    client = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultCookieStore(new BasicCookieStore())
            .setDefaultRequestConfig(getDefaultRequestConfig())
            .setRedirectStrategy(new CustomRedirectStrategy())
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .build();
}
 
Example #4
Source File: HttpSendClientFactory.java    From PoseidonX with Apache License 2.0 6 votes vote down vote up
/**
 * 创建一个{@link HttpSendClient} 实例
 * <p>
 * 多态
 * 
 * @return
 */
public HttpSendClient newHttpSendClient() {
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, getConnectionTimeOut());
    HttpConnectionParams.setSoTimeout(params, getSoTimeOut());
    // HttpConnectionParams.setLinger(params, 1);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    // 解释: 握手的目的,是为了允许客户端在发送请求内容之前,判断源服务器是否愿意接受请求(基于请求头部)。
    // Expect:100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题。
    // 默认开启
    // HttpProtocolParams.setUseExpectContinue(params, false);
    HttpConnectionParams.setTcpNoDelay(params, true);
    HttpConnectionParams.setSocketBufferSize(params, getSocketBufferSize());

    ThreadSafeClientConnManager threadSafeClientConnManager = new ThreadSafeClientConnManager();
    threadSafeClientConnManager.setMaxTotal(getMaxTotalConnections());
    threadSafeClientConnManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute());

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(getRetryCount(), false);

    DefaultHttpClient httpClient = new DefaultHttpClient(threadSafeClientConnManager, params);
    httpClient.setHttpRequestRetryHandler(retryHandler);
    return new HttpSendClient(httpClient);
}
 
Example #5
Source File: SyncHttpClientGenerator.java    From cetty with Apache License 2.0 6 votes vote down vote up
@Override
protected CloseableHttpClient build(Payload payload) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
    if (payload.getUserAgent() != null) {
        httpClientBuilder.setUserAgent(payload.getUserAgent());
    } else {
        httpClientBuilder.setUserAgent("");
    }

    httpClientBuilder.setConnectionManagerShared(true);

    httpClientBuilder.setRedirectStrategy(new CustomRedirectStrategy());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true).setTcpNoDelay(true);
    socketConfigBuilder.setSoTimeout(payload.getSocketTimeout());
    SocketConfig socketConfig = socketConfigBuilder.build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    poolingHttpClientConnectionManager.setDefaultSocketConfig(socketConfig);
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(payload.getRetryTimes(), true));
    reduceCookie(httpClientBuilder, payload);
    return  httpClientBuilder.build();
}
 
Example #6
Source File: HttpProxyUtils.java    From android-uiconductor with Apache License 2.0 6 votes vote down vote up
public static String getRequestAsString(String url)
    throws UicdDeviceHttpConnectionResetException {
  logger.info("get request to xmldumper:" + url);
  String ret = "";
  HttpClient client = HttpClientBuilder.create()
      .setRetryHandler(new DefaultHttpRequestRetryHandler(DEFAULT_REQUEST_RETRIES, true)).build();
  HttpGet method = new HttpGet(url);
  try {
    HttpResponse response = client.execute(method);
    ret = EntityUtils.toString(response.getEntity());
  } catch (IOException e) {
    logger.warning(e.getMessage());
    if (CONNECTION_RESET_KEYWORDS_LIST.stream().parallel().anyMatch(e.getMessage()::contains)) {
      throw new UicdDeviceHttpConnectionResetException(e.getMessage());
    }
  } finally {
    method.releaseConnection();
  }
  return ret;
}
 
Example #7
Source File: HttpConnectionUtil.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a client with all our selected properties / params and SSL enabled.
 * 
 * @return client
 */
public static final HttpClient getSecureClient() {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the ssl verifier to accept all
    client.setSSLHostnameVerifier(new NoopHostnameVerifier());
    // set the connection manager
    client.setConnectionManager(connectionManager);
    // dont retry
    client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    // establish a connection within x seconds
    RequestConfig config = RequestConfig.custom().setSocketTimeout(connectionTimeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    return client.build();
}
 
Example #8
Source File: HttpConnectionUtil.java    From red5-server-common with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a client with all our selected properties / params.
 * 
 * @param timeout
 *            - socket timeout to set
 * @return client
 */
public static final HttpClient getClient(int timeout) {
    HttpClientBuilder client = HttpClientBuilder.create();
    // set the connection manager
    client.setConnectionManager(connectionManager);
    // dont retry
    client.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    // establish a connection within x seconds
    RequestConfig config = RequestConfig.custom().setSocketTimeout(timeout).build();
    client.setDefaultRequestConfig(config);
    // no redirects
    client.disableRedirectHandling();
    // set custom ua
    client.setUserAgent(userAgent);
    // set the proxy if the user has one set
    if ((System.getProperty("http.proxyHost") != null) && (System.getProperty("http.proxyPort") != null)) {
        HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost").toString(), Integer.valueOf(System.getProperty("http.proxyPort")));
        client.setProxy(proxy);
    }
    return client.build();
}
 
Example #9
Source File: HttpHealthcareApiClient.java    From beam with Apache License 2.0 6 votes vote down vote up
private void initClient() throws IOException {

    credentials = GoogleCredentials.getApplicationDefault();
    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        new AuthenticatedRetryInitializer(
            credentials.createScoped(
                CloudHealthcareScopes.CLOUD_PLATFORM, StorageScopes.CLOUD_PLATFORM_READ_ONLY));

    client =
        new CloudHealthcare.Builder(
                new NetHttpTransport(), new JacksonFactory(), requestInitializer)
            .setApplicationName("apache-beam-hl7v2-io")
            .build();
    httpClient =
        HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(10, false)).build();
  }
 
Example #10
Source File: AbstractGoogleClientFactory.java    From nexus-blobstore-google-cloud with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Replicates {@link ApacheHttpTransport#newDefaultHttpClient()} with one exception:
 *
 * 1 retry is allowed.
 *
 * @see DefaultHttpRequestRetryHandler
 */
DefaultHttpClient newDefaultHttpClient(
    SSLSocketFactory socketFactory, HttpParams params, ProxySelector proxySelector) {
  SchemeRegistry registry = new SchemeRegistry();
  registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  registry.register(new Scheme("https", socketFactory, 443));
  ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
  DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
  // retry only once
  defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(1, true));
  if (proxySelector != null) {
    defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));
  }
  defaultHttpClient.setKeepAliveStrategy((response, context) -> KEEP_ALIVE_DURATION);
  return defaultHttpClient;
}
 
Example #11
Source File: NomadApiClient.java    From nomad-java-sdk with Mozilla Public License 2.0 6 votes vote down vote up
private CloseableHttpClient buildHttpClient(NomadApiConfiguration config) {

        return HttpClientBuilder.create()
                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy() {
                    @Override
                    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
                        final long serverKeepAlive = super.getKeepAliveDuration(response, context);
                        return serverKeepAlive > 0 ? serverKeepAlive : 60000;
                    }
                })
                .setRetryHandler(new DefaultHttpRequestRetryHandler() {
                    @Override
                    protected boolean handleAsIdempotent(HttpRequest request) {
                        return true;
                    }
                })
                .setSSLContext(buildSslContext(config.getTls()))
                .setSSLHostnameVerifier(new NomadHostnameVerifier())
                .build();
    }
 
Example #12
Source File: DefaultHttpRequestRetryHandlerModifierIT.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler();
    IOException iOException = new IOException();
    HttpContext context = new BasicHttpContext();
    
    assertTrue(retryHandler.retryRequest(iOException, 1, context));
    assertTrue(retryHandler.retryRequest(iOException, 2, context));
    
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", DefaultHttpRequestRetryHandler.class.getMethod("retryRequest", IOException.class, int.class, HttpContext.class),
            annotation("http.internal.display", IOException.class.getName() + ", 1"), annotation("RETURN_DATA", true)));
    
    verifier.verifyTrace(event("HTTP_CLIENT_4_INTERNAL", DefaultHttpRequestRetryHandler.class.getMethod("retryRequest", IOException.class, int.class, HttpContext.class),
            annotation("http.internal.display", IOException.class.getName() + ", 2"), annotation("RETURN_DATA", true)));

    verifier.verifyTraceCount(0);
}
 
Example #13
Source File: HttpRoutingDataReader.java    From helix with Apache License 2.0 6 votes vote down vote up
/**
 * Makes an HTTP call to fetch all routing data.
 * @return
 * @throws IOException
 */
private static String getAllRoutingData(String msdsEndpoint) throws IOException {
  // Note that MSDS_ENDPOINT should provide high-availability - it risks becoming a single point
  // of failure if it's backed by a single IP address/host
  // Retry count is 3 by default.
  HttpGet requestAllData = new HttpGet(
      msdsEndpoint + MetadataStoreRoutingConstants.MSDS_GET_ALL_ROUTING_DATA_ENDPOINT);

  // Define timeout configs
  RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT_IN_MS)
      .setConnectionRequestTimeout(HTTP_TIMEOUT_IN_MS).setSocketTimeout(HTTP_TIMEOUT_IN_MS)
      .build();

  try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config)
      .setConnectionBackoffStrategy(new DefaultBackoffStrategy())
      .setRetryHandler(new DefaultHttpRequestRetryHandler()).build()) {
    // Return the JSON because try-resources clause closes the CloseableHttpResponse
    HttpEntity entity = httpClient.execute(requestAllData).getEntity();
    if (entity == null) {
      throw new IOException("Response's entity is null!");
    }
    return EntityUtils.toString(entity, "UTF-8");
  }
}
 
Example #14
Source File: ApacheHttpClientFactory.java    From raptor with Apache License 2.0 6 votes vote down vote up
public CloseableHttpClient createHttpClient(HttpClientConnectionManager httpClientConnectionManager,
                                         RaptorHttpClientProperties httpClientProperties) {

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setConnectTimeout(httpClientProperties.getConnectionTimeout())
            .setSocketTimeout(httpClientProperties.getReadTimeout())
            .setRedirectsEnabled(httpClientProperties.isFollowRedirects())
            .build();

    HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(httpClientProperties.getRetryCount(),
            httpClientProperties.isRequestSentRetryEnabled());
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().disableContentCompression()
            .disableCookieManagement()
            .useSystemProperties()
            .setRetryHandler(retryHandler)
            .setConnectionManager(httpClientConnectionManager)
            .setDefaultRequestConfig(defaultRequestConfig);

    if(!keepAlive){
        httpClientBuilder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    }

    return httpClientBuilder.build();
}
 
Example #15
Source File: HttpClientGenerator.java    From zongtui-webcrawler with GNU General Public License v2.0 5 votes vote down vote up
private CloseableHttpClient generateClient(Site site) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager);
    if (site != null && site.getUserAgent() != null) {
        httpClientBuilder.setUserAgent(site.getUserAgent());
    } else {
        httpClientBuilder.setUserAgent("");
    }
    if (site == null || site.isUseGzip()) {
        httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

            public void process(
                    final HttpRequest request,
                    final HttpContext context) throws HttpException, IOException {
                if (!request.containsHeader("Accept-Encoding")) {
                    request.addHeader("Accept-Encoding", "gzip");
                }

            }
        });
    }
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(true).setTcpNoDelay(true).build();
    httpClientBuilder.setDefaultSocketConfig(socketConfig);
    if (site != null) {
        httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(site.getRetryTimes(), true));
    }
    generateCookie(httpClientBuilder, site);
    return httpClientBuilder.build();
}
 
Example #16
Source File: CmmnHttpActivityBehaviorImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected HttpActivityExecutor createHttpActivityExecutor() {
    HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // client builder settings
    if (config.isUseSystemProperties()) {
        httpClientBuilder.useSystemProperties();
    }

    return new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator(),
            CommandContextUtil.getCmmnEngineConfiguration().getObjectMapper());
}
 
Example #17
Source File: JSON.java    From validatar with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a HttpClient to use for making requests.
 *
 * @param metadata The map containing the configuration for this client.
 * @return The created HttpClient object.
 */
private HttpClient createClient(Map<String, String> metadata) {
    int timeout = Integer.valueOf(metadata.getOrDefault(METADATA_TIMEOUT_KEY, String.valueOf(defaultTimeout)));
    int retries = Integer.valueOf(metadata.getOrDefault(METADATA_RETRY_KEY, String.valueOf(defaultRetries)));
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout)
                                                 .setConnectionRequestTimeout(timeout)
                                                 .setSocketTimeout(timeout).build();
    return HttpClientBuilder.create()
                            .setDefaultRequestConfig(config)
                            .setRetryHandler(new DefaultHttpRequestRetryHandler(retries, false))
                            .build();
}
 
Example #18
Source File: ClientBase.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient createHttpClient(String userAgent, Supplier<SSLContext> sslContextSupplier, HostnameVerifier hostnameVerifier) {
    return HttpClientBuilder.create()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(3, /*requestSentRetryEnabled*/true))
            .setUserAgent(userAgent)
            .setSSLSocketFactory(new SSLConnectionSocketFactory(new ServiceIdentitySslSocketFactory(sslContextSupplier), hostnameVerifier))
            .setMaxConnPerRoute(8)
            .setDefaultRequestConfig(RequestConfig.custom()
                                             .setConnectTimeout((int) Duration.ofSeconds(10).toMillis())
                                             .setConnectionRequestTimeout((int)Duration.ofSeconds(10).toMillis())
                                             .setSocketTimeout((int)Duration.ofSeconds(20).toMillis())
                                             .build())
            .build();
}
 
Example #19
Source File: DefaultIdentityDocumentClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static CloseableHttpClient createHttpClient(SSLContext sslContext,
                                                    HostnameVerifier hostnameVerifier) {
    return HttpClientBuilder.create()
            .setRetryHandler(new DefaultHttpRequestRetryHandler(3, /*requestSentRetryEnabled*/true))
            .setSSLContext(sslContext)
            .setSSLHostnameVerifier(hostnameVerifier)
            .setUserAgent("default-identity-document-client")
            .setDefaultRequestConfig(RequestConfig.custom()
                                                .setConnectTimeout((int)Duration.ofSeconds(10).toMillis())
                                                .setConnectionRequestTimeout((int)Duration.ofSeconds(10).toMillis())
                                                .setSocketTimeout((int)Duration.ofSeconds(20).toMillis())
                                                .build())
            .build();
}
 
Example #20
Source File: HttpActivityBehaviorImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected HttpActivityExecutor createHttpActivityExecutor() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // client builder settings
    if (config.isUseSystemProperties()) {
        httpClientBuilder.useSystemProperties();
    }

    return new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator(),
            CommandContextUtil.getProcessEngineConfiguration().getObjectMapper());
}
 
Example #21
Source File: YoutubeIpRotatorRetryHandler.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
  if (exception instanceof BindException) {
    return false;
  } else if (exception instanceof SocketException) {
    String message = exception.getMessage();

    if (message != null && message.contains("Protocol family unavailable")) {
      return false;
    }
  }

  return DefaultHttpRequestRetryHandler.INSTANCE.retryRequest(exception, executionCount, context);
}
 
Example #22
Source File: StreamClientImpl.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    HttpProtocolParams.setUseExpectContinue(globalParams, false);

    // These are some safety settings, we should never run into these timeouts as we
    // do our own expiration checking
    HttpConnectionParams.setConnectionTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, (getConfiguration().getTimeoutSeconds()+5) * 1000);

    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());
    if (getConfiguration().getSocketBufferSize() != -1)
        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());

    // Only register 80, not 443 and SSL
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    clientConnectionManager = new PoolingClientConnectionManager(registry);
    clientConnectionManager.setMaxTotal(getConfiguration().getMaxTotalConnections());
    clientConnectionManager.setDefaultMaxPerRoute(getConfiguration().getMaxTotalPerRoute());

    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
            new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false)
        );
    }
}
 
Example #23
Source File: ApacheHttpTransport.java    From google-http-java-client with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of the Apache HTTP client that is used by the {@link
 * #ApacheHttpTransport()} constructor.
 *
 * @param socketFactory SSL socket factory
 * @param params HTTP parameters
 * @param proxySelector HTTP proxy selector to use {@link ProxySelectorRoutePlanner} or {@code
 *     null} for {@link DefaultHttpRoutePlanner}
 * @return new instance of the Apache HTTP client
 */
static DefaultHttpClient newDefaultHttpClient(
    SSLSocketFactory socketFactory, HttpParams params, ProxySelector proxySelector) {
  // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html
  SchemeRegistry registry = new SchemeRegistry();
  registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
  registry.register(new Scheme("https", socketFactory, 443));
  ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
  DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
  defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
  if (proxySelector != null) {
    defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(registry, proxySelector));
  }
  return defaultHttpClient;
}
 
Example #24
Source File: HttpEndpointBasedTokenMapSupplier.java    From dyno with Apache License 2.0 5 votes vote down vote up
private String getResponseViaHttp(String hostname) throws Exception {

        String url = serverUrl;
        url = url.replace("{hostname}", hostname);

        if (Logger.isDebugEnabled()) {
            Logger.debug("Making http call to url: " + url);
        }

        DefaultHttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 2000);
        client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT, 5000);

        DefaultHttpRequestRetryHandler retryhandler = new DefaultHttpRequestRetryHandler(NUM_RETRIER_ACROSS_NODES,
                true);
        client.setHttpRequestRetryHandler(retryhandler);

        HttpGet get = new HttpGet(url);

        HttpResponse response = client.execute(get);
        int statusCode = response.getStatusLine().getStatusCode();
        if (!(statusCode == 200)) {
            Logger.error("Got non 200 status code from " + url);
            return null;
        }

        InputStream in = null;
        try {
            in = response.getEntity().getContent();
            return IOUtilities.toString(in);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
 
Example #25
Source File: HttpClient.java    From data-prep with Apache License 2.0 5 votes vote down vote up
/**
 * @param connectionManager the connection manager.
 * @return the http client to use backed by a pooling connection manager.
 */
@Bean(destroyMethod = "close")
public CloseableHttpClient getHttpClient(PoolingHttpClientConnectionManager connectionManager) {
    return HttpClientBuilder
            .create() //
            .setConnectionManager(connectionManager) //
            .setKeepAliveStrategy(getKeepAliveStrategy()) //
            .setDefaultRequestConfig(getRequestConfig()) //
            .setConnectionReuseStrategy(DefaultClientConnectionReuseStrategy.INSTANCE) //
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) //
            .setRedirectStrategy(new RedirectTransferStrategy()) //
            .build();
}
 
Example #26
Source File: HttpClient4PluginTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void addDefaultHttpRequestRetryHandlerClass() {
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler();
    IOException iOException = new IOException();
    HttpContext context = new BasicHttpContext();

    assertTrue(retryHandler.retryRequest(iOException, 1, context));
    assertTrue(retryHandler.retryRequest(iOException, 2, context));
}
 
Example #27
Source File: HttpClient4PluginTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void addDefaultHttpRequestRetryHandlerClass() {
    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler();
    IOException iOException = new IOException();
    HttpContext context = new BasicHttpContext();

    assertTrue(retryHandler.retryRequest(iOException, 1, context));
    assertTrue(retryHandler.retryRequest(iOException, 2, context));
}
 
Example #28
Source File: DefaultHttpClientConfigurer.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * Builds the retry handler if {@link #RETRY_SOCKET_EXCEPTION_PROPERTY} is true in the project's configuration.
 *
 * @return the HttpRequestRetryHandler or null depending on configuration
 */
protected HttpRequestRetryHandler buildRetryHandler() {
    // If configured to do so, allow the client to retry once
    if (ConfigContext.getCurrentContextConfig().getBooleanProperty(RETRY_SOCKET_EXCEPTION_PROPERTY, false)) {
        return new DefaultHttpRequestRetryHandler(1, true);
    }

    return null;
}
 
Example #29
Source File: BaseClient.java    From galaxy-sdk-java with Apache License 2.0 5 votes vote down vote up
private HttpClient createHttpClient(ConnectionConfig config) {
  RequestConfig requestConfig = RequestConfig.custom()
      .setConnectTimeout(config.getConnectionTimeoutMs())
      .setSocketTimeout(config.getSocketTimeoutMs())
      .build();

  RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
  registryBuilder.register("http", new PlainConnectionSocketFactory());

  if (config.isHttpsEnabled()) {
    SSLContext sslContext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslContext,
        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    registryBuilder.register("https", sslsf);
  }
  connectionManager = new PoolingHttpClientConnectionManager(registryBuilder.build());
  connectionManager.setDefaultMaxPerRoute(config.getMaxConnection());
  connectionManager.setMaxTotal(config.getMaxConnection());

  HttpClient httpClient = HttpClients.custom()
      .setConnectionManager(connectionManager)
      .setDefaultRequestConfig(requestConfig)
      .setRetryHandler(new DefaultHttpRequestRetryHandler(3, false))
      .build();
  return httpClient;
}
 
Example #30
Source File: SnowizardClient.java    From snowizard with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Get a new CloseableHttpClient
 * 
 * @return CloseableHttpClient
 */
public static CloseableHttpClient newHttpClient() {
    final SocketConfig socketConfig = SocketConfig.custom()
            .setSoKeepAlive(Boolean.TRUE).setTcpNoDelay(Boolean.TRUE)
            .setSoTimeout(SOCKET_TIMEOUT_MS).build();

    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
    manager.setDefaultMaxPerRoute(MAX_HOSTS);
    manager.setMaxTotal(MAX_HOSTS);
    manager.setDefaultSocketConfig(socketConfig);

    final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(CONNECTION_TIMEOUT_MS)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .setStaleConnectionCheckEnabled(Boolean.FALSE)
            .setSocketTimeout(SOCKET_TIMEOUT_MS).build();

    final CloseableHttpClient client = HttpClients
            .custom()
            .disableRedirectHandling()
            .setConnectionManager(manager)
            .setDefaultRequestConfig(requestConfig)
            .setConnectionReuseStrategy(
                    new DefaultConnectionReuseStrategy())
            .setConnectionBackoffStrategy(new DefaultBackoffStrategy())
            .setRetryHandler(
                    new DefaultHttpRequestRetryHandler(MAX_RETRIES, false))
            .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
            .build();
    return client;
}