/** 执行网络访问 */ 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 DefaultConnector() { final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.closeIdleConnections(120, TimeUnit.SECONDS); // would be nice to set this from outside -> keep alive final SocketConfig sConfig = SocketConfig.custom().setSoKeepAlive(true).setSoTimeout(Context.SOCKET_TO).build(); cm.setDefaultSocketConfig(sConfig); cm.setMaxTotal(150); cm.setDefaultMaxPerRoute(150); cm.setValidateAfterInactivity(0); final HttpRequestRetryHandler rh = new DefaultHttpRequestRetryHandler(3, true); httpClient = HttpClients.custom().setRetryHandler(rh).setConnectionManager(cm).build(); }
/** * Builds a custom retry handler that will retry a request up to 20 times if the call fails to connect to the * destination. This is used since startup of nginx and other upstream servers are asynchronous. This smooths * over the "bumpiness" of getting everything started up before we make a call. * * @return The retry handler that will be used by the custom http client. */ static HttpRequestRetryHandler buildRetryHandler() { final int maxRetries = calcMaxRetries(); return (exception, executionCount, context) -> { if (executionCount > maxRetries) { // Do not retry if over max retry count return false; } try { Thread.sleep(getProperties().getMaxNginxStartupPollingTimeMs()); } catch (InterruptedException e) { } // Retry if the server dropped connection on us return true; }; }
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; } }); }
@Deprecated public DefaultRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, new DefaultRedirectStrategyAdaptor(redirectHandler), new AuthenticationStrategyAdaptor(targetAuthHandler), new AuthenticationStrategyAdaptor(proxyAuthHandler), userTokenHandler, params); }
@Deprecated public DefaultRequestDirector( final Log log, final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectStrategy redirectStrategy, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectStrategy, new AuthenticationStrategyAdaptor(targetAuthHandler), new AuthenticationStrategyAdaptor(proxyAuthHandler), userTokenHandler, params); }
/** 执行网络访问 */ 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);//把错误异常交给重试机制,以判断是否需要采取从事 LogUtils.e(e); } } return null; }
/** * 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 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; }
/** This method mainly exists to make the wrapper more testable. oh, apache's insanity. */ protected RequestDirector getRequestDirector(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 DefaultRequestDirector(requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params); }
private static CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname, int port) { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory .getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory .getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( registry); // 将最大连接数增加 cm.setMaxTotal(maxTotal); // 将每个路由基础的连接增加 cm.setDefaultMaxPerRoute(maxPerRoute); // 将目标主机的最大连接数增加 HttpHost httpHost = new HttpHost(hostname, port); cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = (exception, executionCount, context) -> { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; }
/** * @deprecated (4.1) do not use */ @Deprecated protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { return new DefaultRequestDirector( requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, userTokenHandler, params); }
/** * @deprecated (4.2) do not use */ @Deprecated protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectStrategy redirectStrategy, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { return new DefaultRequestDirector( log, requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectStrategy, targetAuthHandler, proxyAuthHandler, userTokenHandler, params); }
/** * @since 4.2 */ protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectStrategy redirectStrategy, final AuthenticationStrategy targetAuthStrategy, final AuthenticationStrategy proxyAuthStrategy, final UserTokenHandler userTokenHandler, final HttpParams params) { return new DefaultRequestDirector( log, requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectStrategy, targetAuthStrategy, proxyAuthStrategy, userTokenHandler, params); }
public static CloseableHttpClient createHttpClient() { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory(); ConnectionSocketFactory sslsf = new EasySSLConnectionSocketFactory(); //SSLConnectionSocketFactory.getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", plainsf) .register("https", sslsf) .build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); // 将最大连接数增加到200 cm.setMaxTotal(200); // 将每个路由基础的连接增加到20 cm.setDefaultMaxPerRoute(20); //请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= 5) {// 如果已经重试了5次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// ssl握手异常 return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler) .build(); return httpClient; }
public static void init() throws RuntimeException { try { logger.warn(NOTICELINE + " httpUtil init begin " + NOTICELINE); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); // sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslContextBuilder.loadTrustMaterial(null,new TrustAnyTrustManager()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create(). register("http", new PlainConnectionSocketFactory()). register("https", sslConnectionSocketFactory). build(); logger.warn(NOTICELINE + " SSL context init done " + NOTICELINE); //init connectionManager , ThreadSafe pooled conMgr PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry); poolingHttpClientConnectionManager.setMaxTotal(30); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(3); //init request config. pooltimeout,sotime,contimeout RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(POOL_TIMECOUT).setConnectTimeout(CON_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build(); // begin construct httpclient HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager); httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= HTTP_RETRY_COUNT) { return false; } if (exception instanceof InterruptedIOException) { // Timeout logger.warn("httpUtil retry for InterruptIOException"); return true; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent logger.warn("httpUtil retry for idempotent"); return true; } return false; } }); logger.warn(NOTICELINE + " poolManager , requestconfig init done " + NOTICELINE); httpclient = httpClientBuilder.build(); logger.warn(NOTICELINE + " httpUtil init done " + NOTICELINE); } catch (Exception e) { logger.error(NOTICELINE + "httpclient init fail" + NOTICELINE, e); throw new RuntimeException(e); } }
public RetryExec( final ClientExecChain requestExecutor, final HttpRequestRetryHandler retryHandler) { Args.notNull(requestExecutor, "HTTP request executor"); Args.notNull(retryHandler, "HTTP request retry handler"); this.requestExecutor = requestExecutor; this.retryHandler = 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; } }); }
/** * 执行网络访问 */ 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); } } } }
public CloseableHttpClient createHttpClient(int maxTotal, int maxPerRoute, int maxRoute, String hostname, int port) { ConnectionSocketFactory plainsf = PlainConnectionSocketFactory .getSocketFactory(); LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory .getSocketFactory(); Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create().register("http", plainsf) .register("https", sslsf).build(); PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager( registry); // 将最大连接数增加 cm.setMaxTotal(maxTotal); // 将每个路由基础的连接增加 cm.setDefaultMaxPerRoute(maxPerRoute); HttpHost httpHost = new HttpHost(hostname, port); // 将目标主机的最大连接数增加 cm.setMaxPerRoute(new HttpRoute(httpHost), maxRoute); // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= _maxRetryTimes) { return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 return false; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return false; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext .adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(cm) .setRetryHandler(httpRequestRetryHandler).build(); return httpClient; }
private AndroidHttpClient(ClientConnectionManager paramClientConnectionManager, HttpParams paramHttpParams) { this.delegate = new DefaultHttpClient(paramClientConnectionManager, paramHttpParams) { protected final RequestDirector createClientRequestDirector(HttpRequestExecutor paramAnonymousHttpRequestExecutor, ClientConnectionManager paramAnonymousClientConnectionManager, ConnectionReuseStrategy paramAnonymousConnectionReuseStrategy, ConnectionKeepAliveStrategy paramAnonymousConnectionKeepAliveStrategy, HttpRoutePlanner paramAnonymousHttpRoutePlanner, HttpProcessor paramAnonymousHttpProcessor, HttpRequestRetryHandler paramAnonymousHttpRequestRetryHandler, RedirectHandler paramAnonymousRedirectHandler, AuthenticationHandler paramAnonymousAuthenticationHandler1, AuthenticationHandler paramAnonymousAuthenticationHandler2, UserTokenHandler paramAnonymousUserTokenHandler, HttpParams paramAnonymousHttpParams) { return new ElegantRequestDirector(paramAnonymousHttpRequestExecutor, paramAnonymousClientConnectionManager, paramAnonymousConnectionReuseStrategy, paramAnonymousConnectionKeepAliveStrategy, paramAnonymousHttpRoutePlanner, paramAnonymousHttpProcessor, paramAnonymousHttpRequestRetryHandler, paramAnonymousRedirectHandler, paramAnonymousAuthenticationHandler1, paramAnonymousAuthenticationHandler2, paramAnonymousUserTokenHandler, paramAnonymousHttpParams); } protected final HttpContext createHttpContext() { BasicHttpContext localBasicHttpContext = new BasicHttpContext(); localBasicHttpContext.setAttribute("http.authscheme-registry", getAuthSchemes()); localBasicHttpContext.setAttribute("http.cookiespec-registry", getCookieSpecs()); localBasicHttpContext.setAttribute("http.auth.credentials-provider", getCredentialsProvider()); return localBasicHttpContext; } protected final BasicHttpProcessor createHttpProcessor() { BasicHttpProcessor localBasicHttpProcessor = super.createHttpProcessor(); localBasicHttpProcessor.addRequestInterceptor(AndroidHttpClient.sThreadCheckInterceptor); localBasicHttpProcessor.addRequestInterceptor(new AndroidHttpClient.CurlLogger(AndroidHttpClient.this, (byte)0)); return localBasicHttpProcessor; } }; }
/** * 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; }
private void configureRetryHandler(DefaultHttpClient httpClient) { httpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { return false; } }); }
/** * 重试策略. * * @return */ private HttpRequestRetryHandler retryPolicy() { return (IOException exception, int executionCount, HttpContext context) -> { // Do not retry if over max retry count if (executionCount >= MAX_RETRY) return false; // Retry if the server dropped connection on us if (exception instanceof NoHttpResponseException) return true; // Do not retry on SSL handshake exception if (exception instanceof SSLHandshakeException) return false; HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); // Retry if the request is considered idempotent return !(request instanceof HttpEntityEnclosingRequest); }; }
/** * 重试(如果请求是幂等的,就再次尝试) * * @param tryTimes 重试次数 * @param retryWhenInterruptedIO 连接拒绝时,是否重试 * @return */ public HCB retry(final int tryTimes, final boolean retryWhenInterruptedIO){ // 请求重试处理 HttpRequestRetryHandler httpRequestRetryHandler = new HttpRequestRetryHandler() { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= tryTimes) {// 如果已经重试了n次,就放弃 return false; } if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试 return true; } if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常 return false; } if (exception instanceof InterruptedIOException) {// 超时 //return false; return retryWhenInterruptedIO; } if (exception instanceof UnknownHostException) {// 目标服务器不可达 return true; } if (exception instanceof ConnectTimeoutException) {// 连接被拒绝 return false; } if (exception instanceof SSLException) {// SSL握手异常 return false; } HttpClientContext clientContext = HttpClientContext .adapt(context); HttpRequest request = clientContext.getRequest(); // 如果请求是幂等的,就再次尝试 if (!(request instanceof HttpEntityEnclosingRequest)) { return true; } return false; } }; this.setRetryHandler(httpRequestRetryHandler); return this; }
public void __constructor__( HttpRequestExecutor requestExec, ClientConnectionManager conman, ConnectionReuseStrategy reustrat, ConnectionKeepAliveStrategy kastrat, HttpRoutePlanner rouplan, HttpProcessor httpProcessor, HttpRequestRetryHandler retryHandler, RedirectHandler redirectHandler, AuthenticationHandler targetAuthHandler, AuthenticationHandler proxyAuthHandler, UserTokenHandler userTokenHandler, HttpParams params) { __constructor__( LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, userTokenHandler, params); }
public DefaultRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler userTokenHandler, final HttpParams params) { this(LogFactory.getLog(DefaultRequestDirector.class), requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, userTokenHandler, params); }
private void init() { // init http client int timeout = 20000; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); HttpConnectionParams.setSoTimeout(httpParams, timeout); mHttpClient = new DefaultHttpClient(httpParams); mHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { logDebug("request retry " + executionCount + ": " + exception.getClass().getName()); if(executionCount < 3) { if(exception instanceof SSLException) { return true; } if(exception instanceof SocketTimeoutException) { return true; } if(exception instanceof ConnectTimeoutException) { return true; } } return false; } }); // init gson & configure it to match server's output format mGson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") .registerTypeAdapter(Notification.Type.class, new GsonNotificationTypeDeserializer()) .create(); }
protected RequestDirector createClientRequestDirector( final HttpRequestExecutor requestExec, final ClientConnectionManager conman, final ConnectionReuseStrategy reustrat, final ConnectionKeepAliveStrategy kastrat, final HttpRoutePlanner rouplan, final HttpProcessor httpProcessor, final HttpRequestRetryHandler retryHandler, final RedirectHandler redirectHandler, final AuthenticationHandler targetAuthHandler, final AuthenticationHandler proxyAuthHandler, final UserTokenHandler stateHandler, final HttpParams params) { return new DefaultRequestDirector( log, requestExec, conman, reustrat, kastrat, rouplan, httpProcessor, retryHandler, redirectHandler, targetAuthHandler, proxyAuthHandler, stateHandler, params); }