FileDocCategorySizeDatePackage
AndroidHttpClientConnection.javaAPI DocAndroid 1.5 API15706Wed May 06 22:41:54 BST 2009android.net.http

AndroidHttpClientConnection

public class AndroidHttpClientConnection extends Object implements HttpConnection, HttpInetConnection
A alternate class for (@link DefaultHttpClientConnection). It has better performance than DefaultHttpClientConnection {@hide}

Fields Summary
private SessionInputBuffer
inbuffer
private SessionOutputBuffer
outbuffer
private int
maxHeaderCount
private int
maxLineLength
private final EntitySerializer
entityserializer
private HttpMessageWriter
requestWriter
private HttpConnectionMetricsImpl
metrics
private volatile boolean
open
private Socket
socket
Constructors Summary
public AndroidHttpClientConnection()


      
        this.entityserializer =  new EntitySerializer(
                new StrictContentLengthStrategy());
    
Methods Summary
private voidassertNotOpen()

        if (this.open) {
            throw new IllegalStateException("Connection is already open");
        }
    
private voidassertOpen()

        if (!this.open) {
            throw new IllegalStateException("Connection is not open");
        }
    
public voidbind(java.net.Socket socket, org.apache.http.params.HttpParams params)
Bind socket and set HttpParams to AndroidHttpClientConnection

param
socket outgoing socket
param
params HttpParams
throws
IOException

        if (socket == null) {
            throw new IllegalArgumentException("Socket may not be null");
        }
        if (params == null) {
            throw new IllegalArgumentException("HTTP parameters may not be null");
        }
        assertNotOpen();
        socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
        socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));

        int linger = HttpConnectionParams.getLinger(params);
        if (linger >= 0) {
            socket.setSoLinger(linger > 0, linger);
        }
        this.socket = socket;

        int buffersize = HttpConnectionParams.getSocketBufferSize(params);
        this.inbuffer = new SocketInputBuffer(socket, buffersize, params);
        this.outbuffer = new SocketOutputBuffer(socket, buffersize, params);

        maxHeaderCount = params.getIntParameter(
                CoreConnectionPNames.MAX_HEADER_COUNT, -1);
        maxLineLength = params.getIntParameter(
                CoreConnectionPNames.MAX_LINE_LENGTH, -1);

        this.requestWriter = new HttpRequestWriter(outbuffer, null, params);

        this.metrics = new HttpConnectionMetricsImpl(
                inbuffer.getMetrics(),
                outbuffer.getMetrics());

        this.open = true;
    
public voidclose()

        if (!this.open) {
            return;
        }
        this.open = false;
        doFlush();
        try {
            try {
                this.socket.shutdownOutput();
            } catch (IOException ignore) {
            }
            try {
                this.socket.shutdownInput();
            } catch (IOException ignore) {
            }
        } catch (UnsupportedOperationException ignore) {
            // if one isn't supported, the other one isn't either
        }
        this.socket.close();
    
private longdetermineLength(Headers headers)

        long transferEncoding = headers.getTransferEncoding();
        // We use Transfer-Encoding if present and ignore Content-Length.
        // RFC2616, 4.4 item number 3
        if (transferEncoding < Headers.NO_TRANSFER_ENCODING) {
            return transferEncoding;
        } else {
            long contentlen = headers.getContentLength();
            if (contentlen > Headers.NO_CONTENT_LENGTH) {
                return contentlen;
            } else {
                return ContentLengthStrategy.IDENTITY;
            }
        }
    
protected voiddoFlush()

        this.outbuffer.flush();
    
public voidflush()

        assertOpen();
        doFlush();
    
public java.net.InetAddressgetLocalAddress()

        if (this.socket != null) {
            return this.socket.getLocalAddress();
        } else {
            return null;
        }
    
public intgetLocalPort()

        if (this.socket != null) {
            return this.socket.getLocalPort();
        } else {
            return -1;
        }
    
public org.apache.http.HttpConnectionMetricsgetMetrics()
Returns a collection of connection metrcis

return
HttpConnectionMetrics

        return this.metrics;
    
public java.net.InetAddressgetRemoteAddress()

        if (this.socket != null) {
            return this.socket.getInetAddress();
        } else {
            return null;
        }
    
public intgetRemotePort()

        if (this.socket != null) {
            return this.socket.getPort();
        } else {
            return -1;
        }
    
public intgetSocketTimeout()

        if (this.socket != null) {
            try {
                return this.socket.getSoTimeout();
            } catch (SocketException ignore) {
                return -1;
            }
        } else {
            return -1;
        }
    
public booleanisOpen()

        // to make this method useful, we want to check if the socket is connected
        return (this.open && this.socket != null && this.socket.isConnected());
    
public booleanisStale()
Checks whether this connection has gone down. Network connections may get closed during some time of inactivity for several reasons. The next time a read is attempted on such a connection it will throw an IOException. This method tries to alleviate this inconvenience by trying to find out if a connection is still usable. Implementations may do that by attempting a read with a very small timeout. Thus this method may block for a small amount of time before returning a result. It is therefore an expensive operation.

return
true if attempts to use this connection are likely to succeed, or false if they are likely to fail and this connection should be closed

        assertOpen();
        try {
            this.inbuffer.isDataAvailable(1);
            return false;
        } catch (IOException ex) {
            return true;
        }
    
public org.apache.http.StatusLineparseResponseHeader(Headers headers)
Parses the response headers and adds them to the given {@code headers} object, and returns the response StatusLine

param
headers store parsed header to headers.
throws
IOException
return
StatusLine
see
HttpClientConnection#receiveResponseHeader()

        assertOpen();

        CharArrayBuffer current = new CharArrayBuffer(64);

        if (inbuffer.readLine(current) == -1) {
            throw new NoHttpResponseException("The target server failed to respond");
        }

        // Create the status line from the status string
        StatusLine statusline = BasicLineParser.DEFAULT.parseStatusLine(
                current, new ParserCursor(0, current.length()));
        
        if (HttpLog.LOGV) HttpLog.v("read: " + statusline);
        int statusCode = statusline.getStatusCode();

        // Parse header body
        CharArrayBuffer previous = null;
        int headerNumber = 0;
        while(true) {
            if (current == null) {
                current = new CharArrayBuffer(64);
            } else {
                // This must be he buffer used to parse the status
                current.clear();
            }
            int l = inbuffer.readLine(current);
            if (l == -1 || current.length() < 1) {
                break;
            }
            // Parse the header name and value
            // Check for folded headers first
            // Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2
            // discussion on folded headers
            char first = current.charAt(0);
            if ((first == ' " || first == '\t") && previous != null) {
                // we have continuation folded header
                // so append value
                int start = 0;
                int length = current.length();
                while (start < length) {
                    char ch = current.charAt(start);
                    if (ch != ' " && ch != '\t") {
                        break;
                    }
                    start++;
                }
                if (maxLineLength > 0 &&
                        previous.length() + 1 + current.length() - start >
                            maxLineLength) {
                    throw new IOException("Maximum line length limit exceeded");
                }
                previous.append(' ");
                previous.append(current, start, current.length() - start);
            } else {
                if (previous != null) {
                    headers.parseHeader(previous);
                }
                headerNumber++;
                previous = current;
                current = null;
            }
            if (maxHeaderCount > 0 && headerNumber >= maxHeaderCount) {
                throw new IOException("Maximum header count exceeded");
            }
        }

        if (previous != null) {
            headers.parseHeader(previous);
        }

        if (statusCode >= 200) {
            this.metrics.incrementResponseCount();
        }
        return statusline;
    
public org.apache.http.HttpEntityreceiveResponseEntity(Headers headers)
Return the next response entity.

param
headers contains values for parsing entity
see
HttpClientConnection#receiveResponseEntity(HttpResponse response)

        assertOpen();
        BasicHttpEntity entity = new BasicHttpEntity();

        long len = determineLength(headers);
        if (len == ContentLengthStrategy.CHUNKED) {
            entity.setChunked(true);
            entity.setContentLength(-1);
            entity.setContent(new ChunkedInputStream(inbuffer));
        } else if (len == ContentLengthStrategy.IDENTITY) {
            entity.setChunked(false);
            entity.setContentLength(-1);
            entity.setContent(new IdentityInputStream(inbuffer));
        } else {
            entity.setChunked(false);
            entity.setContentLength(len);
            entity.setContent(new ContentLengthInputStream(inbuffer, len));
        }

        String contentTypeHeader = headers.getContentType();
        if (contentTypeHeader != null) {
            entity.setContentType(contentTypeHeader);
        }
        String contentEncodingHeader = headers.getContentEncoding();
        if (contentEncodingHeader != null) {
            entity.setContentEncoding(contentEncodingHeader);
        }

       return entity;
    
public voidsendRequestEntity(org.apache.http.HttpEntityEnclosingRequest request)
Sends the request entity over the connection.

param
request the request whose entity to send.
throws
HttpException
throws
IOException

        if (request == null) {
            throw new IllegalArgumentException("HTTP request may not be null");
        }
        assertOpen();
        if (request.getEntity() == null) {
            return;
        }
        this.entityserializer.serialize(
                this.outbuffer,
                request,
                request.getEntity());
    
public voidsendRequestHeader(org.apache.http.HttpRequest request)
Sends the request line and all headers over the connection.

param
request the request whose headers to send.
throws
HttpException
throws
IOException

        if (request == null) {
            throw new IllegalArgumentException("HTTP request may not be null");
        }
        assertOpen();
        this.requestWriter.write(request);
        this.metrics.incrementRequestCount();
    
public voidsetSocketTimeout(int timeout)

        assertOpen();
        if (this.socket != null) {
            try {
                this.socket.setSoTimeout(timeout);
            } catch (SocketException ignore) {
                // It is not quite clear from the original documentation if there are any
                // other legitimate cases for a socket exception to be thrown when setting
                // SO_TIMEOUT besides the socket being already closed
            }
        }
    
public voidshutdown()

        this.open = false;
        Socket tmpsocket = this.socket;
        if (tmpsocket != null) {
            tmpsocket.close();
        }
    
public java.lang.StringtoString()

        StringBuilder buffer = new StringBuilder();
        buffer.append(getClass().getSimpleName()).append("[");
        if (isOpen()) {
            buffer.append(getRemotePort());
        } else {
            buffer.append("closed");
        }
        buffer.append("]");
        return buffer.toString();