org.apache.http.client.HttpRequestRetryHandler源码实例Demo

类org.apache.http.client.HttpRequestRetryHandler源码实例Demo

下面列出了org.apache.http.client.HttpRequestRetryHandler 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: ATest   文件: HttpClientUtil.java
public static CloseableHttpClient getHttpClient(final int executionCount, int retryInterval) {
	ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new MyServiceUnavailableRetryStrategy.Builder()
			.executionCount(executionCount).retryInterval(retryInterval).build();
	return HttpClientBuilder.create().setRetryHandler(new HttpRequestRetryHandler() {
		@Override
		public boolean retryRequest(IOException e, int count, HttpContext contr) {
			if (count >= executionCount) {
				// Do not retry if over max retry count
				return false;
			}
			if (e instanceof InterruptedIOException) {
				// Timeout
				return true;
			}

			return true;
		}
	}).setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
			.setConnectionManager(new PoolingHttpClientConnectionManager()).build();
}
 
源代码2 项目: ATest   文件: HttpClientUtil.java
public static CloseableHttpClient getHttpClient(final int executionCount, int retryInterval) {
	ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new MyServiceUnavailableRetryStrategy.Builder()
			.executionCount(executionCount).retryInterval(retryInterval).build();
	return HttpClientBuilder.create().setRetryHandler(new HttpRequestRetryHandler() {
		@Override
		public boolean retryRequest(IOException e, int count, HttpContext contr) {
			if (count >= executionCount) {
				// Do not retry if over max retry count
				return false;
			}
			if (e instanceof InterruptedIOException) {
				// Timeout
				return true;
			}

			return true;
		}
	}).setServiceUnavailableRetryStrategy(serviceUnavailableRetryStrategy)
			.setConnectionManager(new PoolingHttpClientConnectionManager()).build();
}
 
源代码3 项目: common-mvc   文件: HttpUtils.java
private HttpUtils() {
	cm = new PoolingHttpClientConnectionManager();
	cm.setMaxTotal(500);
	cm.setDefaultMaxPerRoute(100);//例如默认每路由最高50并发,具体依据业务来定
	client = HttpClients.custom()
			.setConnectionManager(cm)
			.setKeepAliveStrategy(keepAliveStrat)
			.setMaxConnPerRoute(100)
			.setRetryHandler(new HttpRequestRetryHandler() {
				@Override
				public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
					return false;  //不需要retry
				}
			})
			.setMaxConnTotal(100)
			.build();
}
 
源代码4 项目: raptor   文件: ApacheHttpClientFactory.java
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();
}
 
private HttpUtilManager() {
	cm = new PoolingHttpClientConnectionManager();
	cm.setMaxTotal(500);
	cm.setDefaultMaxPerRoute(100);//例如默认每路由最高50并发,具体依据业务来定
	client = Init.httpClientBuilder
			.setConnectionManager(cm)
			.setKeepAliveStrategy(keepAliveStrat)
			.setMaxConnPerRoute(100)
			.setRetryHandler(new HttpRequestRetryHandler() {
				@Override
				public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
					return false;  //不需要retry
				}
			})
			.setMaxConnTotal(100)
			.build();
}
 
private HttpUtilManager() {
	cm = new PoolingHttpClientConnectionManager();
	cm.setMaxTotal(500);
	cm.setDefaultMaxPerRoute(100);//例如默认每路由最高50并发,具体依据业务来定
	client = Init.httpClientBuilder
			.setConnectionManager(cm)
			.setKeepAliveStrategy(keepAliveStrat)
			.setMaxConnPerRoute(100)
			.setRetryHandler(new HttpRequestRetryHandler() {
				@Override
				public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
					return false;  //不需要retry
				}
			})
			.setMaxConnTotal(100)
			.build();
}
 
源代码7 项目: letv   文件: HttpEngine.java
private HttpEngine() {
    this.mDefaultHttpClient = null;
    this.mDefaultHttpClient = createHttpClient();
    this.mDefaultHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (DataStatistics.getInstance().isDebug()) {
                Log.d(DataStatistics.TAG, exception.getClass() + NetworkUtils.DELIMITER_COLON + exception.getMessage() + ",executionCount:" + executionCount);
            }
            if (executionCount >= 3) {
                return false;
            }
            if (exception instanceof NoHttpResponseException) {
                return true;
            }
            if (exception instanceof ClientProtocolException) {
                return true;
            }
            return false;
        }
    });
}
 
源代码8 项目: soabase   文件: ClientBuilder.java
public HttpClient buildHttpClient(HttpClientConfiguration configuration, String clientName)
{
    Preconditions.checkState(providers.size() == 0, "HttpClient does not support providers");
    Preconditions.checkState(providerClasses.size() == 0, "HttpClient does not support providers");
    Preconditions.checkState(connectorProvider == null, "HttpClient does not support ConnectorProvider");

    HttpRequestRetryHandler nullRetry = new HttpRequestRetryHandler()
    {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context)
        {
            return false;
        }
    };

    HttpClient httpClient = new HttpClientBuilder(environment)
        .using(configuration)
        .using(nullRetry)  // Apache's retry mechanism does not allow changing hosts. Do retries manually
        .build(clientName);
    HttpClient client = new WrappedHttpClient(httpClient, retryComponents);

    SoaBundle.getFeatures(environment).putNamed(client, HttpClient.class, clientName);

    return client;
}
 
源代码9 项目: google-http-java-client   文件: MockHttpClient.java
@Override
protected RequestDirector createClientRequestDirector(
    HttpRequestExecutor requestExec,
    ClientConnectionManager conman,
    ConnectionReuseStrategy reustrat,
    ConnectionKeepAliveStrategy kastrat,
    HttpRoutePlanner rouplan,
    HttpProcessor httpProcessor,
    HttpRequestRetryHandler retryHandler,
    RedirectHandler redirectHandler,
    AuthenticationHandler targetAuthHandler,
    AuthenticationHandler proxyAuthHandler,
    UserTokenHandler stateHandler,
    HttpParams params) {
  return new RequestDirector() {
    @Beta
    public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context)
        throws HttpException, IOException {
      return new BasicHttpResponse(HttpVersion.HTTP_1_1, responseCode, null);
    }
  };
}
 
源代码10 项目: miappstore   文件: HttpHelper.java
/** 执行网络访问 */
private static HttpResult execute(String url, HttpRequestBase requestBase) {
	boolean isHttps = url.startsWith("https://");//判断是否需要采用https
	AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
	HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
	HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler();//获取重试机制
	int retryCount = 0;
	boolean retry = true;
	while (retry) {
		try {
			HttpResponse response = httpClient.execute(requestBase, httpContext);//访问网络
			if (response != null) {
				return new HttpResult(response, httpClient, requestBase);
			}
		} catch (Exception e) {
			IOException ioException = new IOException(e.getMessage());
			retry = retryHandler.retryRequest(ioException, ++retryCount, httpContext);//把错误异常交给重试机制,以判断是否需要采取从事
		}
	}
	return null;
}
 
public AzureCloudInstanceInformationProcessor(HelixCloudProperty helixCloudProperty) {
  _helixCloudProperty = helixCloudProperty;

  RequestConfig requestConifg = RequestConfig.custom()
      .setConnectionRequestTimeout((int) helixCloudProperty.getCloudRequestTimeout())
      .setConnectTimeout((int) helixCloudProperty.getCloudConnectionTimeout()).build();

  HttpRequestRetryHandler httpRequestRetryHandler =
      (IOException exception, int executionCount, HttpContext context) -> {
        LOG.warn("Execution count: " + executionCount + ".", exception);
        return !(executionCount >= helixCloudProperty.getCloudMaxRetry()
            || exception instanceof InterruptedIOException
            || exception instanceof UnknownHostException || exception instanceof SSLException);
      };

  //TODO: we should regularize the way how httpClient should be used throughout Helix. e.g. Helix-rest could also use in the same way
  _closeableHttpClient = HttpClients.custom().setDefaultRequestConfig(requestConifg)
      .setRetryHandler(httpRequestRetryHandler).build();
}
 
源代码12 项目: carbon-apimgt   文件: HttpLoadTestClient.java
@Override
public void run() {
    SchemeRegistry supportedSchemes = new SchemeRegistry();
    SocketFactory sf = PlainSocketFactory.getSocketFactory();
    supportedSchemes.register(new Scheme("http", sf, 80));
    ThreadSafeClientConnManager connManager = new ThreadSafeClientConnManager(supportedSchemes);
    connManager.setDefaultMaxPerRoute(1000);
    DefaultHttpClient client = new DefaultHttpClient(connManager);
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
    //test API call
    long t1 = System.currentTimeMillis();
    testEndpoint(client,apiEndpoint);
    long t2 = System.currentTimeMillis();
    timeElapsedForAPICall = t2 - t1;


}
 
源代码13 项目: rice   文件: DefaultHttpClientConfigurer.java
/**
 * Customizes the configuration of the httpClientBuilder.
 *
 * <p>Internally, this uses several helper methods to assist with configuring:
 * <ul>
 *     <li>Calls {@link #buildConnectionManager()} and sets the resulting {@link HttpClientConnectionManager} (if
 *     non-null) into the httpClientBuilder.</li>
 *     <li>Calls {@link #buildRequestConfig()} and sets the resulting {@link RequestConfig} (if non-null) into the
 *     httpClientBuilder.</li>
 *     <li>Calls {@link #buildRetryHandler()} and sets the resulting {@link HttpRequestRetryHandler} (if non-null)
 *     into the httpClientBuilder.</li>
 * </ul>
 * </p>
 *
 * @param httpClientBuilder the httpClientBuilder being configured
 */
@Override
public void customizeHttpClient(HttpClientBuilder httpClientBuilder) {

    HttpClientConnectionManager connectionManager = buildConnectionManager();
    if (connectionManager != null) {
        httpClientBuilder.setConnectionManager(connectionManager);
    }

    RequestConfig requestConfig = buildRequestConfig();
    if (requestConfig != null) {
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    HttpRequestRetryHandler retryHandler = buildRetryHandler();
    if (retryHandler != null) {
        httpClientBuilder.setRetryHandler(retryHandler);
    }
}
 
源代码14 项目: micro-integrator   文件: SimpleHttpClient.java
public SimpleHttpClient() {
    this.client = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
源代码15 项目: micro-integrator   文件: SOAPClient.java
/**
 * Sets up the client
 */
private void setup() {
    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
    httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
源代码16 项目: micro-integrator   文件: RESTClient.java
/**
 * Sets up the client
 */
private void setup() {
    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
    httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
源代码17 项目: vividus   文件: HttpClientConfigTests.java
@Test
void testGetAndSetHttpRequestRetryHandler()
{
    HttpRequestRetryHandler handler = mock(HttpRequestRetryHandler.class);
    config.setHttpRequestRetryHandler(handler);
    assertEquals(handler, config.getHttpRequestRetryHandler());
}
 
源代码18 项目: pay-spring-boot   文件: HttpClient.java
private HttpClient(){
    /**
     * 请求配置
     */
    RequestConfig globalConfig = RequestConfig.
                                    custom().
                                    setCookieSpec(CookieSpecs.DEFAULT).
                                    setSocketTimeout(10000).
                                    setConnectTimeout(20000).
                                    setConnectionRequestTimeout(20000).
                                    build();
    /**
     * cookie容器
     */
    CookieStore cookieStore = new BasicCookieStore();
    
    /**
     * 核心请求对象
     */
    httpclient = HttpClients.
                    custom().
                    setDefaultRequestConfig(globalConfig).
                    setDefaultCookieStore(cookieStore).
                    setRetryHandler(new HttpRequestRetryHandler() {
                        @Override
                        public boolean retryRequest(IOException exception, int retryTimes, HttpContext httpContext) {
                            if(retryTimes > 10){  //最多重试10次
                                return false;
                            }
                            if(Arrays.asList(InterruptedIOException.class, UnknownHostException.class, ConnectException.class, SSLException.class).contains(exception.getClass())){  //此类异常不进行重试
                                return false;
                            }
                            return true;  //重点是这,非幂等的post请求也进行重试
                        }
                    }).
                    build();
}
 
源代码19 项目: pushfish-android   文件: HttpClientConfigurer.java
private void configureRetryHandler(DefaultHttpClient httpClient) {
    httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });
}
 
源代码20 项目: pushfish-android   文件: HttpClientConfigurer.java
private void configureRetryHandler(DefaultHttpClient httpClient) {
    httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });
}
 
源代码21 项目: caravan   文件: PoolingHttpClientFactory.java
public static CloseableHttpClient create(RequestConfig config, HttpRequestRetryHandler retryHandler, int maxConnectionsPerRoute, int maxTotalConnections,
        int connectionTtl, int inactivityTimeBeforeValidate, int connectionIdleTime, int cleanCheckInteval) {
    AutoCleanedPoolingHttpClientConnectionManager manager = new AutoCleanedPoolingHttpClientConnectionManager(connectionTtl, inactivityTimeBeforeValidate,
            connectionIdleTime, cleanCheckInteval);
    manager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
    manager.setMaxTotal(maxTotalConnections);
    return create(config, retryHandler, manager);
}
 
源代码22 项目: caravan   文件: PoolingHttpClientFactory.java
public static CloseableHttpClient create(RequestConfig config, HttpRequestRetryHandler retryHandler, HttpClientConnectionManager connectionManager) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.useSystemProperties().setRedirectStrategy(AlwaysRedirectStrategy.DEFAULT).addInterceptorLast(new RequestContent(true));
    if (config != null)
        builder.setDefaultRequestConfig(config);
    if (retryHandler != null)
        builder.setRetryHandler(retryHandler);
    if (connectionManager != null)
        builder.setConnectionManager(connectionManager);
    return builder.build();
}
 
源代码23 项目: sdk   文件: AviRestUtils.java
/**
 * This method sets a custom HttpRequestRetryHandler in order to enable a custom
 * exception recovery mechanism.
 * 
 * @return A HttpRequestRetryHandler representing handling of the retryHandler.
 */
private static HttpRequestRetryHandler retryHandler(AviCredentials creds) {
	return (exception, executionCount, context) -> {

		if (executionCount >= creds.getNumApiRetries()) {
			// Do not retry if over max retry count
			return false;
		}
		if (exception instanceof InterruptedIOException) {
			// Timeout
			return false;
		}
		if (exception instanceof UnknownHostException) {
			// Unknown host
			return false;
		}
		if (exception instanceof SSLException) {
			// SSL handshake exception
			return false;
		}
		if (exception instanceof HttpHostConnectException) {
			return true;
		}
		HttpClientContext clientContext = HttpClientContext.adapt(context);
		HttpRequest request = clientContext.getRequest();
		boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
		if (idempotent) {
			// Retry if the request is considered idempotent
			return true;
		}
		return false;
	};
}
 
源代码24 项目: product-ei   文件: SimpleHttpClient.java
public SimpleHttpClient() {
    this.client = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = client.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 30000);
    HttpConnectionParams.setSoTimeout(params, 30000);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
源代码25 项目: product-ei   文件: SOAPClient.java
/**
 * Sets up the client
 */
private void setup() {
    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
    httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
源代码26 项目: product-ei   文件: RESTClient.java
/**
 * Sets up the client
 */
private void setup() {
    httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
    HttpParams params = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
    httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
            return false;
        }
    });
}
 
源代码27 项目: NetEasyNews   文件: HttpHelper.java
/**
     * 执行网络访问
     */
    private static void execute(String url, HttpRequestBase requestBase, HttpCallbackListener httpCallbackListener) {
        boolean isHttps = url.startsWith("https://");//判断是否需要采用https
        AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
        HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
        HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler();//获取重试机制
        int retryCount = 0;
        boolean retry = true;
        while (retry) {
            try {
                HttpResponse response = httpClient.execute(requestBase, httpContext);//访问网络
                int stateCode  = response.getStatusLine().getStatusCode();
//                LogUtils.e(TAG, "http状态码:" + stateCode);
                if (response != null) {
                    if (stateCode == HttpURLConnection.HTTP_OK){
                        HttpResult httpResult = new HttpResult(response, httpClient, requestBase);
                        String result = httpResult.getString();
                        if (!TextUtils.isEmpty(result)){
                            httpCallbackListener.onSuccess(result);
                            return;
                        } else {
                            throw new RuntimeException("数据为空");
                        }
                    } else {
                        throw new RuntimeException(HttpRequestCode.ReturnCode(stateCode));
                    }
                }
            } catch (Exception e) {
                IOException ioException = new IOException(e.getMessage());
                retry = retryHandler.retryRequest(ioException, ++retryCount, httpContext);//把错误异常交给重试机制,以判断是否需要采取从事
                LogUtils.e(TAG, "重复次数:" + retryCount + "   :"+ e);
                if (!retry){
                    httpCallbackListener.onError(e);
                }
            }
        }
    }
 
源代码28 项目: Pushjet-Android   文件: HttpClientConfigurer.java
private void configureRetryHandler(DefaultHttpClient httpClient) {
    httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });
}
 
源代码29 项目: Pushjet-Android   文件: HttpClientConfigurer.java
private void configureRetryHandler(DefaultHttpClient httpClient) {
    httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });
}
 
源代码30 项目: yuzhouwan   文件: HttpUtils.java
/**
 * 初始化 httpClient 客户端.
 */
private HttpClientBuilder initHttpClient(PoolingHttpClientConnectionManager httpClientConnectionManager,
                                         RequestConfig defaultRequestConfig, LaxRedirectStrategy redirectStrategy,
                                         HttpRequestRetryHandler retryHandler) {
    return HttpClients.custom()
            .setConnectionManager(httpClientConnectionManager).setDefaultRequestConfig(defaultRequestConfig)
            .setRedirectStrategy(redirectStrategy).setRetryHandler(retryHandler);
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法