public static void statistics() { if (mCache != null) { Log.d( TAG, "request count:" + HttpCache.getRequestCount(mCache) + ",network count:" + HttpCache.getNetworkCount(mCache) + ",hit count:" + HttpCache.getHitCount(mCache)); } }
public static void statistics(Context context) { if (mCache != null) { Toast.makeText( context, "request count:" + HttpCache.getRequestCount(mCache) + ",network count:" + HttpCache.getNetworkCount(mCache) + ",hit count:" + HttpCache.getHitCount(mCache), Toast.LENGTH_SHORT) .show(); } }
@Test public void testInvalidateUrl() throws Exception { cache.addResponse(new HttpRequest(URI), CACHEABLE); assertEquals(1, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); service.invalidateApplicationResources(ImmutableSet.of(URI), appxToken); assertEquals(0, cacheProvider.createCache(DefaultHttpCache.CACHE_NAME).getSize()); }
private static void installCacheIfNeeded(Context context) { if (mCache == null) { synchronized (NetworkUtils.class) { if (mCache == null) { mCache = HttpCache.install(context); } } } }
@Test public void testFetchInvalidatedContent() throws Exception { // Prime the cache cache.addResponse(new HttpRequest(URI), CACHEABLE); // Invalidate the entry service.invalidateApplicationResources(ImmutableSet.of(URI), appxToken); fetcher.response = new HttpResponseBuilder(CACHEABLE).setResponseString("NEWCONTENT1").create(); assertEquals(requestPipeline.execute(new HttpRequest(URI)), fetcher.response); }
public class HttpUtils { public static final HttpCache sHttpCache = new HttpCache(); private final DefaultHttpClient httpClient; private final HttpContext httpContext = new BasicHttpContext(); private HttpRedirectHandler httpRedirectHandler; private ISecureInterceptor secureInterceptor = new SimpleSecurityHandler(); public HttpUtils() { this(HttpUtils.DEFAULT_CONN_TIMEOUT, null); } public HttpUtils(int connTimeout) { this(connTimeout, null); } public HttpUtils(String userAgent) { this(HttpUtils.DEFAULT_CONN_TIMEOUT, userAgent); } public HttpUtils(int connTimeout, String userAgent) { HttpParams params = new BasicHttpParams(); ConnManagerParams.setTimeout(params, connTimeout); HttpConnectionParams.setSoTimeout(params, connTimeout); HttpConnectionParams.setConnectionTimeout(params, connTimeout); if (TextUtils.isEmpty(userAgent)) { userAgent = OtherUtils.getUserAgent(null); } HttpProtocolParams.setUserAgent(params, userAgent); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(10)); ConnManagerParams.setMaxTotalConnections(params, 10); HttpConnectionParams.setTcpNoDelay(params, true); HttpConnectionParams.setSocketBufferSize(params, 1024 * 8); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); schemeRegistry.register(new Scheme("https", DefaultSSLSocketFactory.getSocketFactory(), 443)); httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params, schemeRegistry), params); httpClient.setHttpRequestRetryHandler(new RetryHandler(DEFAULT_RETRY_TIMES)); httpClient.addRequestInterceptor( new HttpRequestInterceptor() { @Override public void process(org.apache.http.HttpRequest httpRequest, HttpContext httpContext) throws org.apache.http.HttpException, IOException { if (!httpRequest.containsHeader(HEADER_ACCEPT_ENCODING)) { httpRequest.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); httpClient.addResponseInterceptor( new HttpResponseInterceptor() { @Override public void process(HttpResponse response, HttpContext httpContext) throws org.apache.http.HttpException, IOException { final HttpEntity entity = response.getEntity(); if (entity == null) { return; } final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase("gzip")) { response.setEntity(new GZipDecompressingEntity(response.getEntity())); return; } } } } }); } // ************************************ default settings & fields // **************************** private String responseTextCharset = HTTP.UTF_8; private long currentRequestExpiry = HttpCache.getDefaultExpiryTime(); private static final int DEFAULT_CONN_TIMEOUT = 1000 * 15; // 15s private static final int DEFAULT_RETRY_TIMES = 2; private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; private static final String ENCODING_GZIP = "gzip"; private static final int DEFAULT_POOL_SIZE = 2; private static final PriorityExecutor EXECUTOR = new PriorityExecutor(DEFAULT_POOL_SIZE); public HttpClient getHttpClient() { return this.httpClient; } // ***************************************** config // ******************************************* // 配置网络请求的安全验证器.liuzw. public void configSecureInterceptor(ISecureInterceptor interceptor) { if (interceptor == null) return; this.secureInterceptor = interceptor; } public HttpUtils configResponseTextCharset(String charSet) { if (!TextUtils.isEmpty(charSet)) { this.responseTextCharset = charSet; } return this; } public HttpUtils configHttpRedirectHandler(HttpRedirectHandler httpRedirectHandler) { this.httpRedirectHandler = httpRedirectHandler; return this; } public HttpUtils configHttpCacheSize(int httpCacheSize) { sHttpCache.setCacheSize(httpCacheSize); return this; } public HttpUtils configDefaultHttpCacheExpiry(long defaultExpiry) { HttpCache.setDefaultExpiryTime(defaultExpiry); currentRequestExpiry = HttpCache.getDefaultExpiryTime(); return this; } public HttpUtils configCurrentHttpCacheExpiry(long currRequestExpiry) { this.currentRequestExpiry = currRequestExpiry; return this; } public HttpUtils configCookieStore(CookieStore cookieStore) { httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); return this; } public HttpUtils configUserAgent(String userAgent) { HttpProtocolParams.setUserAgent(this.httpClient.getParams(), userAgent); return this; } public HttpUtils configTimeout(int timeout) { final HttpParams httpParams = this.httpClient.getParams(); ConnManagerParams.setTimeout(httpParams, timeout); HttpConnectionParams.setConnectionTimeout(httpParams, timeout); return this; } public HttpUtils configSoTimeout(int timeout) { final HttpParams httpParams = this.httpClient.getParams(); HttpConnectionParams.setSoTimeout(httpParams, timeout); return this; } public HttpUtils configRegisterScheme(Scheme scheme) { this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme); return this; } public HttpUtils configSSLSocketFactory(SSLSocketFactory sslSocketFactory) { Scheme scheme = new Scheme("https", sslSocketFactory, 443); this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme); return this; } public HttpUtils configRequestRetryCount(int count) { this.httpClient.setHttpRequestRetryHandler(new RetryHandler(count)); return this; } public HttpUtils configRequestThreadPoolSize(int threadPoolSize) { HttpUtils.EXECUTOR.setPoolSize(threadPoolSize); return this; } // ***************************************** send request // ******************************************* public <T> HttpHandler<T> send( HttpRequest.HttpMethod method, String url, RequestCallBack<T> callBack) { return send(method, url, null, callBack); } public <T> HttpHandler<T> send( HttpRequest.HttpMethod method, String url, RequestParams params, RequestCallBack<T> callBack) { if (url == null) throw new IllegalArgumentException("url may not be null"); HttpRequest request = new HttpRequest(method, url); return sendRequest(request, params, callBack); } public ResponseStream sendSync(HttpRequest.HttpMethod method, String url) throws HttpException { return sendSync(method, url, null); } public ResponseStream sendSync(HttpRequest.HttpMethod method, String url, RequestParams params) throws HttpException { if (url == null) throw new IllegalArgumentException("url may not be null"); HttpRequest request = new HttpRequest(method, url); return sendSyncRequest(request, params); } // ***************************************** download // ******************************************* public HttpHandler<File> download(String url, String target, RequestCallBack<File> callback) { return download(HttpRequest.HttpMethod.GET, url, target, null, false, false, callback); } public HttpHandler<File> download( String url, String target, boolean autoResume, RequestCallBack<File> callback) { return download(HttpRequest.HttpMethod.GET, url, target, null, autoResume, false, callback); } public HttpHandler<File> download( String url, String target, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) { return download( HttpRequest.HttpMethod.GET, url, target, null, autoResume, autoRename, callback); } public HttpHandler<File> download( String url, String target, RequestParams params, RequestCallBack<File> callback) { return download(HttpRequest.HttpMethod.GET, url, target, params, false, false, callback); } public HttpHandler<File> download( String url, String target, RequestParams params, boolean autoResume, RequestCallBack<File> callback) { return download(HttpRequest.HttpMethod.GET, url, target, params, autoResume, false, callback); } public HttpHandler<File> download( String url, String target, RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) { return download( HttpRequest.HttpMethod.GET, url, target, params, autoResume, autoRename, callback); } public HttpHandler<File> download( HttpRequest.HttpMethod method, String url, String target, RequestParams params, RequestCallBack<File> callback) { return download(method, url, target, params, false, false, callback); } public HttpHandler<File> download( HttpRequest.HttpMethod method, String url, String target, RequestParams params, boolean autoResume, RequestCallBack<File> callback) { return download(method, url, target, params, autoResume, false, callback); } public HttpHandler<File> download( HttpRequest.HttpMethod method, String url, String target, RequestParams params, boolean autoResume, boolean autoRename, RequestCallBack<File> callback) { if (url == null) throw new IllegalArgumentException("url may not be null"); if (target == null) throw new IllegalArgumentException("target may not be null"); HttpRequest request = new HttpRequest(method, url); HttpHandler<File> handler = new HttpHandler<File>(httpClient, httpContext, responseTextCharset, callback); handler.setExpiry(currentRequestExpiry); handler.setHttpRedirectHandler(httpRedirectHandler); if (params != null) { request.setRequestParams(params, handler); handler.setPriority(params.getPriority()); } handler.executeOnExecutor(EXECUTOR, request, target, autoResume, autoRename); return handler; } // ////////////////////////////////////////////////////////////////////////////////////////////// private <T> HttpHandler<T> sendRequest( HttpRequest request, RequestParams params, RequestCallBack<T> callBack) { // liuzw. 增加安全加密步骤,加密过程可定制. if (secureInterceptor != null) { params = secureInterceptor.preSend(request, params); } HttpHandler<T> handler = new HttpHandler<T>(httpClient, httpContext, responseTextCharset, callBack); handler.setExpiry(currentRequestExpiry); handler.setHttpRedirectHandler(httpRedirectHandler); request.setRequestParams(params, handler); if (params != null) { handler.setPriority(params.getPriority()); } handler.executeOnExecutor(EXECUTOR, request); return handler; } private ResponseStream sendSyncRequest(HttpRequest request, RequestParams params) throws HttpException { // liuzw. 增加安全加密步骤,加密过程可定制. if (secureInterceptor != null) { params = secureInterceptor.preSend(request, params); } SyncHttpHandler handler = new SyncHttpHandler(httpClient, httpContext, responseTextCharset); handler.setExpiry(currentRequestExpiry); handler.setHttpRedirectHandler(httpRedirectHandler); request.setRequestParams(params); return handler.sendRequest(request); } }
public HttpUtils configDefaultHttpCacheExpiry(long defaultExpiry) { HttpCache.setDefaultExpiryTime(defaultExpiry); currentRequestExpiry = HttpCache.getDefaultExpiryTime(); return this; }
public HttpUtils configHttpCacheSize(int httpCacheSize) { sHttpCache.setCacheSize(httpCacheSize); return this; }
@Test public void testFetchWithInvalidationEnabled() throws Exception { cache.addResponse(new HttpRequest(URI), CACHEABLE); assertEquals(CACHEABLE, requestPipeline.execute(new HttpRequest(URI))); }
public static void shutDown() { if (mCache != null) { HttpCache.close(mCache); } }
private static void uninstallCache() { if (mCache != null) { HttpCache.delete(mCache); } }
public class SyncHttpHandler { private final AbstractHttpClient client; private final HttpContext context; private HttpRedirectHandler httpRedirectHandler; public void setHttpRedirectHandler(HttpRedirectHandler httpRedirectHandler) { this.httpRedirectHandler = httpRedirectHandler; } private String requestUrl; private String requestMethod; private String charset; // The default charset of response header info. private int retriedTimes = 0; public SyncHttpHandler(AbstractHttpClient client, HttpContext context, String charset) { this.client = client; this.context = context; this.charset = charset; } private long expiry = HttpCache.getDefaultExpiryTime(); public void setExpiry(long expiry) { this.expiry = expiry; } public ResponseStream sendRequest(HttpRequestBase request) throws HttpException { HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler(); while (true) { boolean retry = true; IOException exception = null; try { requestUrl = request.getURI().toString(); requestMethod = request.getMethod(); if (HttpUtils.sHttpCache.isEnabled(requestMethod)) { String result = HttpUtils.sHttpCache.get(requestUrl); if (result != null) { return new ResponseStream(result); } } HttpResponse response = client.execute(request, context); return handleResponse(response); } catch (UnknownHostException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (IOException e) { exception = e; retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (NullPointerException e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } catch (HttpException e) { throw e; } catch (Throwable e) { exception = new IOException(e.getMessage()); exception.initCause(e); retry = retryHandler.retryRequest(exception, ++retriedTimes, context); } if (!retry) { throw new HttpException(exception); } } } private ResponseStream handleResponse(HttpResponse response) throws HttpException, IOException { if (response == null) { throw new HttpException("response is null"); } StatusLine status = response.getStatusLine(); int statusCode = status.getStatusCode(); if (statusCode < 300) { ResponseStream responseStream = new ResponseStream(response, charset, requestUrl, expiry); responseStream.setRequestMethod(requestMethod); return responseStream; } else if (statusCode == 301 || statusCode == 302) { if (httpRedirectHandler == null) { httpRedirectHandler = new DefaultHttpRedirectHandler(); } HttpRequestBase request = httpRedirectHandler.getDirectRequest(response); if (request != null) { return this.sendRequest(request); } } else if (statusCode == 416) { throw new HttpException(statusCode, "maybe the file has downloaded completely"); } else { throw new HttpException(statusCode, status.getReasonPhrase()); } return null; } }