下面列出了org.apache.http.impl.client.TargetAuthenticationStrategy#org.apache.http.client.HttpRequestRetryHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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();
}
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();
}
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();
}
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();
}
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;
}
});
}
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;
}
@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);
}
};
}
/** 执行网络访问 */
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();
}
@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;
}
/**
* 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);
}
}
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;
}
});
}
/**
* 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;
}
});
}
/**
* 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;
}
});
}
@Test
void testGetAndSetHttpRequestRetryHandler()
{
HttpRequestRetryHandler handler = mock(HttpRequestRetryHandler.class);
config.setHttpRequestRetryHandler(handler);
assertEquals(handler, config.getHttpRequestRetryHandler());
}
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();
}
private void configureRetryHandler(DefaultHttpClient httpClient) {
httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
});
}
private void configureRetryHandler(DefaultHttpClient httpClient) {
httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
});
}
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);
}
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();
}
/**
* 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;
};
}
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;
}
});
}
/**
* 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;
}
});
}
/**
* 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;
}
});
}
/**
* 执行网络访问
*/
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);
}
}
}
}
private void configureRetryHandler(DefaultHttpClient httpClient) {
httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
});
}
private void configureRetryHandler(DefaultHttpClient httpClient) {
httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
});
}
/**
* 初始化 httpClient 客户端.
*/
private HttpClientBuilder initHttpClient(PoolingHttpClientConnectionManager httpClientConnectionManager,
RequestConfig defaultRequestConfig, LaxRedirectStrategy redirectStrategy,
HttpRequestRetryHandler retryHandler) {
return HttpClients.custom()
.setConnectionManager(httpClientConnectionManager).setDefaultRequestConfig(defaultRequestConfig)
.setRedirectStrategy(redirectStrategy).setRetryHandler(retryHandler);
}