Example usage for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler

List of usage examples for org.apache.http.impl.client DefaultHttpRequestRetryHandler DefaultHttpRequestRetryHandler

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public DefaultHttpRequestRetryHandler(final int retryCount, final boolean requestSentRetryEnabled) 

Source Link

Document

Create the request retry handler using the following list of non-retriable IOException classes:
  • InterruptedIOException
  • UnknownHostException
  • ConnectException
  • SSLException

Usage

From source file:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java

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 ThreadSafeClientConnManager(globalParams, 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));
    }//from   w w  w. j  ava  2s .  co m
}

From source file:uk.co.unclealex.googleauth.ApacheHttpTransport.java

/**
 * Creates a new instance of the Apache HTTP client that is used by the
 * {@link #ApacheHttpTransport()} constructor.
 *
 * <p>// w w w .  jav  a2 s  .c  om
 * Use this constructor if you want to customize the default Apache HTTP client. Settings:
 * </p>
 * <ul>
 * <li>The client connection manager is set to {@link ThreadSafeClientConnManager}.</li>
 * <li>The socket buffer size is set to 8192 using
 * {@link HttpConnectionParams#setSocketBufferSize}.</li>
 * <li><The retry mechanism is turned off by setting
 * {@code new DefaultHttpRequestRetryHandler(0, false)}</li>
 * </ul>
 *
 * @return new instance of the Apache HTTP client
 * @since 1.6
 */
public static DefaultHttpClient newDefaultHttpClient() {
    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setStaleCheckingEnabled(params, false);
    HttpConnectionParams.setSocketBufferSize(params, 8192);
    ConnManagerParams.setMaxTotalConnections(params, 200);
    ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(20));
    // 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", SSLSocketFactory.getSocketFactory(), 443));
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connectionManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
    return defaultHttpClient;
}

From source file:com.msopentech.thali.utilities.universal.HttpKeyHttpClient.java

public HttpKeyHttpClient(PublicKey serverPublicKey, KeyStore clientKeyStore, char[] clientKeyStorePassPhrase,
        Proxy proxy, HttpParams params)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    super(params);
    schemeRegistry = new SchemeRegistry();
    HttpKeySSLSocketFactory httpKeySSLSocketFactory = new HttpKeySSLSocketFactory(serverPublicKey,
            clientKeyStore, clientKeyStorePassPhrase);
    schemeRegistry.register((new Scheme("https", httpKeySSLSocketFactory, 443)));

    // Try to up retries to deal with how flakey the Tor Hidden Service channels seem to be.
    // Note that modern Apache would set this via a Param but that Param doesn't seem to exist
    // in Android land. This sucks because we can't be sure if the user is using the default
    // retry handler or different one. And no, comparing getHttpRequestRetryHandler() against
    // DefaultHttpRequestRetryHandler.INSTANCE doesn't work. :( In fact, INSTANCE isn't even available
    // in Android.
    if (proxy != null && this.getHttpRequestRetryHandler() instanceof DefaultHttpRequestRetryHandler) {
        DefaultHttpRequestRetryHandler currentHandler = (DefaultHttpRequestRetryHandler) this
                .getHttpRequestRetryHandler();
        if (currentHandler.getRetryCount() < torProxyRequestRetryCount) {
            this.setHttpRequestRetryHandler(
                    new DefaultHttpRequestRetryHandler(torProxyRequestRetryCount, true));
        }//from w  w  w  .j  a v  a  2 s .  c om
    }

    this.proxy = proxy;
}

From source file:org.teleal.cling.transport.impl.apache.StreamClientImpl.java

public StreamClientImpl(StreamClientConfigurationImpl configuration) throws InitializationException {
    this.configuration = configuration;

    ConnManagerParams.setMaxTotalConnections(globalParams, getConfiguration().getMaxTotalConnections());
    HttpConnectionParams.setConnectionTimeout(globalParams,
            getConfiguration().getConnectionTimeoutSeconds() * 1000);
    HttpConnectionParams.setSoTimeout(globalParams, getConfiguration().getDataReadTimeoutSeconds() * 1000);
    HttpProtocolParams.setContentCharset(globalParams, getConfiguration().getContentCharset());
    if (getConfiguration().getSocketBufferSize() != -1) {

        // Android configuration will set this to 8192 as its httpclient is
        // based/*from  w  ww .j a va  2s. c o m*/
        // on a random pre 4.0.1 snapshot whose BasicHttpParams do not set a
        // default value for socket buffer size.
        // This will also avoid OOM on the HTC Thunderbolt where default
        // size is 2Mb (!):
        // http://stackoverflow.com/questions/5358014/android-httpclient-oom-on-4g-lte-htc-thunderbolt

        HttpConnectionParams.setSocketBufferSize(globalParams, getConfiguration().getSocketBufferSize());
    }
    HttpConnectionParams.setStaleCheckingEnabled(globalParams, getConfiguration().getStaleCheckingEnabled());

    // This is a pretty stupid API...
    // https://issues.apache.org/jira/browse/HTTPCLIENT-805
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // The
    // 80
    // here
    // is...
    // useless
    clientConnectionManager = new ThreadSafeClientConnManager(globalParams, registry);
    httpClient = new DefaultHttpClient(clientConnectionManager, globalParams);
    if (getConfiguration().getRequestRetryCount() != -1) {
        httpClient.setHttpRequestRetryHandler(
                new DefaultHttpRequestRetryHandler(getConfiguration().getRequestRetryCount(), false));
    }

    /*
     * // TODO: Ugh! And it turns out that by default it doesn't even use
     * persistent connections properly!
     * 
     * @Override protected ConnectionReuseStrategy
     * createConnectionReuseStrategy() { return new
     * NoConnectionReuseStrategy(); }
     * 
     * @Override protected ConnectionKeepAliveStrategy
     * createConnectionKeepAliveStrategy() { return new
     * ConnectionKeepAliveStrategy() { public long
     * getKeepAliveDuration(HttpResponse httpResponse, HttpContext
     * httpContext) { return 0; } }; }
     * httpClient.removeRequestInterceptorByClass(RequestConnControl.class);
     */
}

From source file:org.lol.reddit.cache.CacheManager.java

private CacheManager(final Context context) {

    if (!isAlreadyInitialized.compareAndSet(false, true)) {
        throw new RuntimeException("Attempt to initialize the cache twice.");
    }/*from   w  w  w .  ja v a 2 s.  c o  m*/

    this.context = context;

    dbManager = new CacheDbManager(context);

    RequestHandlerThread requestHandler = new RequestHandlerThread();

    // TODo put somewhere else -- make request specific, no restart needed on prefs change!
    final HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.USER_AGENT, Constants.ua(context));
    params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000); // TODO remove hardcoded params, put in network prefs
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
    params.setParameter(CoreConnectionPNames.MAX_HEADER_COUNT, 100);
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, true);
    params.setParameter(ClientPNames.MAX_REDIRECTS, 5);
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 50);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRoute() {
        public int getMaxForRoute(HttpRoute route) {
            return 25;
        }
    });

    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

    final ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(params, schemeRegistry);

    final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(connManager, params);
    defaultHttpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    defaultHttpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {

            final HttpEntity entity = response.getEntity();
            final Header encHeader = entity.getContentEncoding();

            if (encHeader == null)
                return;

            for (final HeaderElement elem : encHeader.getElements()) {
                if ("gzip".equalsIgnoreCase(elem.getName())) {
                    response.setEntity(new GzipDecompressingEntity(entity));
                    return;
                }
            }
        }
    });

    downloadQueue = new PrioritisedDownloadQueue(defaultHttpClient);

    requestHandler.start();
}

From source file:jetbrains.buildServer.commitPublisher.github.api.impl.HttpClientWrapperImpl.java

public HttpClientWrapperImpl()
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final String serverVersion = ServerVersionHolder.getVersion().getDisplayVersion();

    final HttpParams ps = new BasicHttpParams();

    DefaultHttpClient.setDefaultHttpParams(ps);
    final int timeout = TeamCityProperties.getInteger("teamcity.github.http.timeout", 300 * 1000);
    HttpConnectionParams.setConnectionTimeout(ps, timeout);
    HttpConnectionParams.setSoTimeout(ps, timeout);
    HttpProtocolParams.setUserAgent(ps, "JetBrains TeamCity " + serverVersion);

    final SchemeRegistry schemaRegistry = SchemeRegistryFactory.createDefault();
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return !TeamCityProperties.getBoolean("teamcity.github.verify.ssl.certificate");
        }/*from  ww w.j  a  v  a2  s .co  m*/
    }) {
        @Override
        public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host,
                InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context)
                throws IOException {
            if (socket instanceof SSLSocket) {
                try {
                    PropertyUtils.setProperty(socket, "host", host.getHostName());
                } catch (Exception ex) {
                    LOG.warn(String.format(
                            "A host name is not passed to SSL connection for the purpose of supporting SNI due to the following exception: %s",
                            ex.toString()));
                }
            }
            return super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
        }
    };
    schemaRegistry.register(new Scheme("https", 443, sslSocketFactory));

    final DefaultHttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager(schemaRegistry),
            ps);

    setupProxy(httpclient);

    httpclient.setRoutePlanner(new ProxySelectorRoutePlanner(
            httpclient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()));
    httpclient.addRequestInterceptor(new RequestAcceptEncoding());
    httpclient.addResponseInterceptor(new ResponseContentEncoding());
    httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(3, true));

    myClient = httpclient;
}

From source file:org.ops4j.pax.url.mvn.internal.HttpClients.java

private static HttpRequestRetryHandler createRetryHandler(PropertyResolver resolver, String pid) {
    int retryCount = getInteger(resolver, pid + ServiceConstants.PROPERTY_CONNECTION_RETRY_COUNT, 3);
    return new DefaultHttpRequestRetryHandler(retryCount, false);
}

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  ww. j a v  a  2  s .  co m
        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();
}

From source file:net.timbusproject.extractors.pojo.CallBack.java

public synchronized void doCallBack(long key, RequestExtractionList extractionList, boolean success)
        throws URISyntaxException, IOException {
    CallBackInfo info = extractionList.getCallbackInfo();
    System.out.println("IN CALLBACK. REQUEST TYPE: " + info.getFinalOriginRequestType());
    if (info == null)
        System.out.println("No callback information provided");
    else {/*from ww w. j  av a  2 s  . c o m*/
        if (info.getMails() != null) {
            setMailConfiguration();
            for (String a : info.getMails()) {
                System.out.println("Email adress is: " + a);
                if (isValidEmailAddress(a)) {
                    sendEmail(a, "End of extraction request",
                            "The extractions were completed. Please, check out /extractors/api/requests/ to view the results");
                    System.out.println("Sent email: " + a);
                }
            }
        } else
            System.out.println("No e-mail adress(es) provided");
        if (info.getEndPoints() != null) {
            for (String a : info.getEndPoints()) {
                HttpResponse response;
                if (info.requestType != null && info.requestType.toLowerCase().equals("post")) {
                    try {
                        JSONObject jsonResult = new JSONObject().put("id", key);
                        if (success)
                            jsonResult.put("result", "completed");
                        else
                            jsonResult.put("result", "failed");
                        DefaultHttpClient httpClient = new DefaultHttpClient();
                        HttpPost postRequest = new HttpPost(a);
                        postRequest.setEntity(new StringEntity(jsonResult.toString(),
                                ContentType.create("application/json")));
                        response = httpClient.execute(postRequest);
                        System.out.println("Sent POST request to " + a);
                        System.out.println("Endpoint " + a + " says: " + response.getStatusLine());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("Sending GET request to: " + a);
                    String uri = a;
                    if (!uri.startsWith("http://"))
                        uri = "http://" + uri;
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
                    response = httpClient.execute(new HttpGet(uri));
                    System.out.println("Sent GET request to " + uri);
                    System.out.println("Endpoint " + a + " says: " + response.getStatusLine());
                }
            }
        } else {
            System.out.println("No foreign endpoints for callback provided");
        }
        if (info.getOriginEndpoint() != null) {
            HttpResponse response;
            if (info.getFinalOriginRequestType().equals("post")) {
                System.out
                        .println("Preparing POST request for endpoint " + "http://" + info.getOriginEndpoint());
                try {
                    JSONObject jsonResult = new JSONObject().put("id", key);
                    if (success)
                        jsonResult.put("result", "completed");
                    else
                        jsonResult.put("result", "failed");
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost postRequest = new HttpPost("http://" + info.getOriginEndpoint());
                    postRequest.setEntity(
                            new StringEntity(jsonResult.toString(), ContentType.create("application/json")));
                    response = httpClient.execute(postRequest);
                    System.out.println("Sent POST request to " + "http://" + info.getOriginEndpoint());
                    System.out.println("Endpoint " + "http://" + info.getOriginEndpoint() + " says: "
                            + response.getStatusLine());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                System.out
                        .println("Preparing GET request for endpoint " + "http://" + info.getOriginEndpoint());
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
                response = httpClient.execute(new HttpGet("http://" + info.getOriginEndpoint()));
            }
        } else {
            System.out.println("No port or path provided for origin endpoint callback");
        }
    }
}