FileDocCategorySizeDatePackage
AndroidHttpClient.javaAPI DocAndroid 5.1 API20527Thu Mar 12 22:22:10 GMT 2015android.net.http

AndroidHttpClient

public final class AndroidHttpClient extends Object implements HttpClient
Implementation of the Apache {@link DefaultHttpClient} that is configured with reasonable default settings and registered schemes for Android. Don't create this directly, use the {@link #newInstance} factory method.

This client processes cookies but does not retain them by default. To retain cookies, simply add a cookie store to the HttpContext:

context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
deprecated
Please use {@link java.net.URLConnection} and friends instead. The Apache HTTP client is no longer maintained and may be removed in a future release. Please visit this webpage for further details.

Fields Summary
public static long
DEFAULT_SYNC_MIN_GZIP_BYTES
private static final int
SOCKET_OPERATION_TIMEOUT
private static final String
TAG
private static String[]
textContentTypes
private static final HttpRequestInterceptor
sThreadCheckInterceptor
Interceptor throws an exception if the executing thread is blocked
private final HttpClient
delegate
private RuntimeException
mLeakedException
private volatile LoggingConfiguration
curlConfiguration
cURL logging configuration.
Constructors Summary
private AndroidHttpClient(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());

                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;
            }
        };
    
Methods Summary
public voidclose()
Release resources associated with this client. You must call this, or significant resources (sockets and memory) may be leaked.

        if (mLeakedException != null) {
            getConnectionManager().shutdown();
            mLeakedException = null;
        }
    
public voiddisableCurlLogging()
Disables cURL logging for this client.

        curlConfiguration = null;
    
public voidenableCurlLogging(java.lang.String name, int level)
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})

        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);
    
public org.apache.http.HttpResponseexecute(org.apache.http.client.methods.HttpUriRequest request)

        return delegate.execute(request);
    
public org.apache.http.HttpResponseexecute(org.apache.http.client.methods.HttpUriRequest request, org.apache.http.protocol.HttpContext context)

        return delegate.execute(request, context);
    
public org.apache.http.HttpResponseexecute(org.apache.http.HttpHost target, org.apache.http.HttpRequest request)

        return delegate.execute(target, request);
    
public org.apache.http.HttpResponseexecute(org.apache.http.HttpHost target, org.apache.http.HttpRequest request, org.apache.http.protocol.HttpContext context)

        return delegate.execute(target, request, context);
    
public Texecute(org.apache.http.client.methods.HttpUriRequest request, org.apache.http.client.ResponseHandler responseHandler)

        return delegate.execute(request, responseHandler);
    
public Texecute(org.apache.http.client.methods.HttpUriRequest request, org.apache.http.client.ResponseHandler responseHandler, org.apache.http.protocol.HttpContext context)

        return delegate.execute(request, responseHandler, context);
    
public Texecute(org.apache.http.HttpHost target, org.apache.http.HttpRequest request, org.apache.http.client.ResponseHandler responseHandler)

        return delegate.execute(target, request, responseHandler);
    
public Texecute(org.apache.http.HttpHost target, org.apache.http.HttpRequest request, org.apache.http.client.ResponseHandler responseHandler, org.apache.http.protocol.HttpContext context)

        return delegate.execute(target, request, responseHandler, context);
    
protected voidfinalize()

        super.finalize();
        if (mLeakedException != null) {
            Log.e(TAG, "Leak found", mLeakedException);
            mLeakedException = null;
        }
    
public static org.apache.http.entity.AbstractHttpEntitygetCompressedEntity(byte[] data, android.content.ContentResolver resolver)
Compress data to send to server. Creates a Http Entity holding the gzipped data. The data will not be compressed if it is too short.

param
data The bytes to compress
return
Entity holding the data

        AbstractHttpEntity entity;
        if (data.length < getMinGzipSize(resolver)) {
            entity = new ByteArrayEntity(data);
        } else {
            ByteArrayOutputStream arr = new ByteArrayOutputStream();
            OutputStream zipper = new GZIPOutputStream(arr);
            zipper.write(data);
            zipper.close();
            entity = new ByteArrayEntity(arr.toByteArray());
            entity.setContentEncoding("gzip");
        }
        return entity;
    
public org.apache.http.conn.ClientConnectionManagergetConnectionManager()

        return delegate.getConnectionManager();
    
public static longgetMinGzipSize(android.content.ContentResolver resolver)
Retrieves the minimum size for compressing data. Shorter data will not be compressed.

        return DEFAULT_SYNC_MIN_GZIP_BYTES;  // For now, this is just a constant.
    
public org.apache.http.params.HttpParamsgetParams()

        return delegate.getParams();
    
public static java.io.InputStreamgetUngzippedContent(org.apache.http.HttpEntity entity)
Gets the input stream from a response entity. If the entity is gzipped then this will get a stream over the uncompressed data.

param
entity the entity whose content should be read
return
the input stream to read from
throws
IOException

        InputStream responseStream = entity.getContent();
        if (responseStream == null) return responseStream;
        Header header = entity.getContentEncoding();
        if (header == null) return responseStream;
        String contentEncoding = header.getValue();
        if (contentEncoding == null) return responseStream;
        if (contentEncoding.contains("gzip")) responseStream
                = new GZIPInputStream(responseStream);
        return responseStream;
    
private static booleanisBinaryContent(org.apache.http.client.methods.HttpUriRequest request)

        Header[] headers;
        headers = request.getHeaders(Headers.CONTENT_ENCODING);
        if (headers != null) {
            for (Header header : headers) {
                if ("gzip".equalsIgnoreCase(header.getValue())) {
                    return true;
                }
            }
        }

        headers = request.getHeaders(Headers.CONTENT_TYPE);
        if (headers != null) {
            for (Header header : headers) {
                for (String contentType : textContentTypes) {
                    if (header.getValue().startsWith(contentType)) {
                        return false;
                    }
                }
            }
        }
        return true;
    
public static voidmodifyRequestToAcceptGzipResponse(org.apache.http.HttpRequest request)
Modifies a request to indicate to the server that we would like a gzipped response. (Uses the "Accept-Encoding" HTTP header.)

param
request the request to modify
see
#getUngzippedContent

        request.addHeader("Accept-Encoding", "gzip");
    
public static android.net.http.AndroidHttpClientnewInstance(java.lang.String userAgent, android.content.Context context)
Create a new HttpClient with reasonable defaults (which you can update).

param
userAgent to report in your HTTP requests
param
context to use for caching SSL sessions (may be null for no caching)
return
AndroidHttpClient for you to use for all your requests.
deprecated
Please use {@link java.net.URLConnection} and friends instead. See {@link android.net.SSLCertificateSocketFactory} for SSL cache support. If you'd like to set a custom useragent, please use {@link java.net.URLConnection#setRequestProperty(String, String)} with {@code field} set to {@code User-Agent}.


                                                                                                   
    
           
        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);

        HttpConnectionParams.setConnectionTimeout(params, SOCKET_OPERATION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SOCKET_OPERATION_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);

        // Use a session cache for SSL sockets
        SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);

        // Set the specified user agent and register standard protocols.
        HttpProtocolParams.setUserAgent(params, userAgent);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http",
                PlainSocketFactory.getSocketFactory(), 80));
        schemeRegistry.register(new Scheme("https",
                SSLCertificateSocketFactory.getHttpSocketFactory(
                SOCKET_OPERATION_TIMEOUT, sessionCache), 443));

        ClientConnectionManager manager =
                new ThreadSafeClientConnManager(params, schemeRegistry);

        // We use a factory method to modify superclass initialization
        // parameters without the funny call-a-static-method dance.
        return new AndroidHttpClient(manager, params);
    
public static android.net.http.AndroidHttpClientnewInstance(java.lang.String userAgent)
Create a new HttpClient with reasonable defaults (which you can update).

param
userAgent to report in your HTTP requests.
return
AndroidHttpClient for you to use for all your requests.
deprecated
Please use {@link java.net.URLConnection} and friends instead. See {@link android.net.SSLCertificateSocketFactory} for SSL cache support. If you'd like to set a custom useragent, please use {@link java.net.URLConnection#setRequestProperty(String, String)} with {@code field} set to {@code User-Agent}.

        return newInstance(userAgent, null /* session cache */);
    
public static longparseDate(java.lang.String dateString)
Returns the date of the given HTTP date string. This method can identify and parse the date formats emitted by common HTTP servers, such as RFC 822, RFC 850, RFC 1036, RFC 1123 and ANSI C's asctime().

return
the number of milliseconds since Jan. 1, 1970, midnight GMT.
throws
IllegalArgumentException if {@code dateString} is not a date or of an unsupported format.

        return HttpDateTime.parse(dateString);
    
private static java.lang.StringtoCurl(org.apache.http.client.methods.HttpUriRequest request, boolean logAuthToken)
Generates a cURL command equivalent to the given request.

        StringBuilder builder = new StringBuilder();

        builder.append("curl ");

        // add in the method
        builder.append("-X ");
        builder.append(request.getMethod());
        builder.append(" ");

        for (Header header: request.getAllHeaders()) {
            if (!logAuthToken
                    && (header.getName().equals("Authorization") ||
                        header.getName().equals("Cookie"))) {
                continue;
            }
            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);

                    if (isBinaryContent(request)) {
                        String base64 = Base64.encodeToString(stream.toByteArray(), Base64.NO_WRAP);
                        builder.insert(0, "echo '" + base64 + "' | base64 -d > /tmp/$$.bin; ");
                        builder.append(" --data-binary @/tmp/$$.bin");
                    } else {
                        String entityString = stream.toString();
                        builder.append(" --data-ascii \"")
                                .append(entityString)
                                .append("\"");
                    }
                } else {
                    builder.append(" [TOO MUCH DATA TO INCLUDE]");
                }
            }
        }

        return builder.toString();