Java tutorial
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.devtcg.five.util.streaming; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URI; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.params.HttpClientParams; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.client.RequestWrapper; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import android.util.Log; /** * Subclass of the Apache {@link DefaultHttpClient} that is configured with * reasonable default settings and registered schemes for Android, and * also lets the user add {@link HttpRequestInterceptor} classes. * Don't create this directly, use the {@link #newInstance} factory method. * * <p>This client processes cookies but does not retain them by default. * To retain cookies, simply add a cookie store to the HttpContext:</p> * * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre> * * <p>Uses an alternate ClientConnectionManager ultimately to work around * a harmony socket closure bug on Linux.</p> */ public final class FailfastHttpClient implements HttpClient { private static final String TAG = "FailfastHttpClient"; private static final int CONNECT_TIMEOUT = 20 * 1000; private static final int READ_TIMEOUT = 15 * 1000; /** Set if HTTP requests are blocked from being executed on this thread */ private static final ThreadLocal<Boolean> sThreadBlocked = new ThreadLocal<Boolean>(); /** Interceptor throws an exception if the executing thread is blocked */ private static final HttpRequestInterceptor sThreadCheckInterceptor = new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { if (sThreadBlocked.get() != null && sThreadBlocked.get()) { throw new RuntimeException("This thread forbids HTTP requests"); } } }; /** * Create a new HttpClient with reasonable defaults (which you can update). * @param userAgent to report in your HTTP requests. * @return FailfastHttpClient for you to use for all your requests. */ public static FailfastHttpClient newInstance(String userAgent) { HttpParams params = new BasicHttpParams(); // 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. HttpConnectionParams.setStaleCheckingEnabled(params, false); // Default connection and socket timeout of 10 seconds. Tweak to taste. HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT); HttpConnectionParams.setSoTimeout(params, READ_TIMEOUT); HttpConnectionParams.setSocketBufferSize(params, 8192); // Don't handle redirects -- return them to the caller. Our code // often wants to re-POST after a redirect, which we must do ourselves. HttpClientParams.setRedirecting(params, false); // Set the specified user agent and register standard protocols. if (userAgent != null) HttpProtocolParams.setUserAgent(params, userAgent); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager manager = new HackThreadSafeClientConnManager(params, schemeRegistry); // We use a factory method to modify superclass initialization // parameters without the funny call-a-static-method dance. return new FailfastHttpClient(manager, params); } private final DefaultHttpClient delegate; private RuntimeException mLeakedException = new IllegalStateException( "FailfastHttpClient created and never closed"); private FailfastHttpClient(ClientConnectionManager ccm, HttpParams params) { this.delegate = new DefaultHttpClient(ccm, params) { @Override protected BasicHttpProcessor createHttpProcessor() { // Add interceptor to prevent making requests from main thread. BasicHttpProcessor processor = super.createHttpProcessor(); processor.addRequestInterceptor(sThreadCheckInterceptor); processor.addRequestInterceptor(new CurlLogger()); /* * Add as the very first interceptor, according to the tutorial * (no idea why that's required). */ processor.addRequestInterceptor(new PreemptiveAuth(), 0); return processor; } @Override protected HttpContext createHttpContext() { // Same as DefaultHttpClient.createHttpContext() minus the // cookie store. HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes()); context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs()); context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider()); return context; } }; } @Override protected void finalize() throws Throwable { super.finalize(); if (mLeakedException != null) { Log.e(TAG, "Leak found", mLeakedException); mLeakedException = null; } } /** * Block this thread from executing HTTP requests. * Used to guard against HTTP requests blocking the main application thread. * @param blocked if HTTP requests run on this thread should be denied */ public static void setThreadBlocked(boolean blocked) { sThreadBlocked.set(blocked); } /** * Release resources associated with this client. You must call this, * or significant resources (sockets and memory) may be leaked. */ public void close() { if (mLeakedException != null) { getConnectionManager().shutdown(); mLeakedException = null; } } public HttpParams getParams() { return delegate.getParams(); } public ClientConnectionManager getConnectionManager() { return delegate.getConnectionManager(); } public CredentialsProvider getCredentialsProvider() { return delegate.getCredentialsProvider(); } public HttpResponse execute(HttpUriRequest request) throws IOException { return delegate.execute(request); } public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException { return delegate.execute(request, context); } public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException { return delegate.execute(target, request); } public HttpResponse execute(HttpHost target, HttpRequest request, HttpContext context) throws IOException { return delegate.execute(target, request, context); } public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { return delegate.execute(request, responseHandler); } public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException { return delegate.execute(request, responseHandler, context); } public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler) throws IOException, ClientProtocolException { return delegate.execute(target, request, responseHandler); } public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context) throws IOException, ClientProtocolException { return delegate.execute(target, request, responseHandler, context); } /* cURL logging support. */ /** * Logging tag and level. */ private static class LoggingConfiguration { private final String tag; private final int level; private LoggingConfiguration(String tag, int level) { this.tag = tag; this.level = level; } /** * Returns true if logging is turned on for this configuration. */ private boolean isLoggable() { return Log.isLoggable(tag, level); } /** * Prints a message using this configuration. */ private void println(String message) { Log.println(level, tag, message); } } /** cURL logging configuration. */ private volatile LoggingConfiguration curlConfiguration; /** * Enables cURL request logging for this client. * * @param name to log messages with * @param level at which to log messages (see {@link android.util.Log}) */ public void enableCurlLogging(String name, int level) { if (name == null) { throw new NullPointerException("name"); } if (level < Log.VERBOSE || level > Log.ASSERT) { throw new IllegalArgumentException("Level is out of range [" + Log.VERBOSE + ".." + Log.ASSERT + "]"); } curlConfiguration = new LoggingConfiguration(name, level); } /** * Disables cURL logging for this client. */ public void disableCurlLogging() { curlConfiguration = null; } /** * Logs cURL commands equivalent to requests. */ private class CurlLogger implements HttpRequestInterceptor { public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { LoggingConfiguration configuration = curlConfiguration; if (configuration != null && configuration.isLoggable() && request instanceof HttpUriRequest) { configuration.println(toCurl((HttpUriRequest) request)); } } } /** * Generates a cURL command equivalent to the given request. */ private static String toCurl(HttpUriRequest request) throws IOException { StringBuilder builder = new StringBuilder(); builder.append("curl "); for (Header header : request.getAllHeaders()) { builder.append("--header \""); builder.append(header.toString().trim()); builder.append("\" "); } URI uri = request.getURI(); // If this is a wrapped request, use the URI from the original // request instead. getURI() on the wrapper seems to return a // relative URI. We want an absolute URI. if (request instanceof RequestWrapper) { HttpRequest original = ((RequestWrapper) request).getOriginal(); if (original instanceof HttpUriRequest) { uri = ((HttpUriRequest) original).getURI(); } } builder.append("\""); builder.append(uri); builder.append("\""); if (request instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; HttpEntity entity = entityRequest.getEntity(); if (entity != null && entity.isRepeatable()) { if (entity.getContentLength() < 1024) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); entity.writeTo(stream); String entityString = stream.toString(); // TODO: Check the content type, too. builder.append(" --data-ascii \"").append(entityString).append("\""); } else { builder.append(" [TOO MUCH DATA TO INCLUDE]"); } } } return builder.toString(); } /* * Taken from the HttpComponents-Client tutorial at: * * http://hc.apache.org/httpcomponents-client/tutorial/html/authentication.html#d4e942 */ private static class PreemptiveAuth implements HttpRequestInterceptor { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); // If not auth scheme has been initialized yet if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } } }