⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 protocol.java

📁 用于移动设备上的java虚拟机源代码
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/* * @(#)Protocol.java	1.117 02/10/14 @(#) * * Copyright (c) 1999-2002 Sun Microsystems, Inc.  All rights reserved. * PROPRIETARY/CONFIDENTIAL * Use is subject to license terms. */package com.sun.midp.io.j2me.http;/** * A class representing a http connection. An http connection consists of * stream connection as well as input and output streams for read/write data to * and from a web server. This version supports HTTP1.1 persistent connections * allowing connects to be shared from a connection pool. This pool and the * maximum number of connections can be configured for a particular platform. * Proxy connections are also allowed through this interface. * * <p> The actual connection to the web server does not take place until the * application needs an, (1) input stream, (2) flush data, (3)request some  * header info or closes the connection (with outstanding data in the  * output stream). Because of this issue the state transition must allow for * some flexability to move backwards for WRITE state conditions. * * <p> Persistent connections are provided through the use of a connection * pool that tracks the connect status. There are maximum threshold values * defined and these values can be overiden using property key/value pars. * The connection pool provides a synchronized interface for managing the * maximum configurable connections. Persistent connections will only be  * supported for HTTP1.1 connections - otherwise the connections will be * closed and disgarded after its done (HTTP1.0 behavior). * * <p> This class extends the ConnectionBaseAdapter where Connector type * objects (like this) use various features. Output and Input streams are * created and managed in the adapter class. * * <p> The reading and writing of data through the input and output streams * are configured, buffered and managed depending on the ability of a  * platform to read/write on those streams.  * */import java.io.IOException;import java.io.InputStream;import java.io.InterruptedIOException;import java.io.OutputStream;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.ByteArrayOutputStream;import java.util.Enumeration;import java.util.Hashtable;import javax.microedition.io.SocketConnection;import javax.microedition.io.StreamConnection;import javax.microedition.io.HttpConnection;import javax.microedition.io.Connector;import javax.microedition.io.Connection;import javax.microedition.io.ConnectionNotFoundException;import com.sun.midp.main.Configuration;import com.sun.midp.io.ConnectionBaseAdapter;import com.sun.midp.io.HttpUrl;import com.sun.midp.io.NetworkConnectionBase;import com.sun.midp.io.Properties;import com.sun.midp.io.DateParser;import com.sun.midp.security.SecurityToken;import com.sun.midp.security.Permissions;/** * This class implements the necessary functionality * for an HTTP connection. */public class Protocol extends ConnectionBaseAdapter     implements HttpConnection  {    /** HTTP version string to use with all outgoing HTTP requests. */    protected static final String HTTP_VERSION = "HTTP/1.1";    /** Where to start the data in the output buffer. */    private static final int HTTP_OUTPUT_DATA_OFFSET = 24;    /** How must extra room for the chunk terminator. */    private static final int HTTP_OUTPUT_EXTRA_ROOM = 8;    /** This class has a different security domain than the MIDlet suite */    private static SecurityToken classSecurityToken;        /** Default size for input buffer. */         private static int inputBufferSize = 256;    /** Default size for output buffer. */    private static int outputBufferSize = 2048;    /** How much data can be put in the output buffer. */    private static int outputDataSize;    /** The "host:port" value to use for HTTP proxied requests. */    private static String http_proxy;    /** Maximum number of persistent connections. */    private static int maxNumberOfPersistentConnections = 1;    /** Connection linger time in the pool, default 60 seconds. */    private static long connectionLingerTime = 60000;    /** Persistent connection pool. */    private static StreamConnectionPool connectionPool;     /** True if com.sun.midp.io.http.force_non_persistent = true. */    private static boolean nonPersistentFlag;    /** Get the configuration values for this class. */    static {        String prop;        int temp;        /*         * Get the proxy here instead of the connector,         * so when this method subclassed by HTTPS http_proxy will be null         * and the proxy will not be added into the request.         */        http_proxy = Configuration.getProperty("com.sun.midp.io.http.proxy");                /*         * if first time intialize the connection pool and create         * a connection (you could create more)         */        maxNumberOfPersistentConnections = 1;        /*         * bug#4455443 - allows for configuration options to shut off          * the persistent connection feature for http          */        String flag =             Configuration.getProperty(                                "com.sun.midp.io.http.force_non_persistent");        if ((flag != null) && (flag.equals("true"))) {            nonPersistentFlag = true;        }        /*         * Get the  maximum number of persistent connections         * from the configuration file.         */        prop = Configuration.getProperty(                            "com.sun.midp.io.http.max_persistent_connections");        if (prop != null) {            try {                temp = Integer.parseInt(prop);                if (temp <= 0) {                    maxNumberOfPersistentConnections = temp;                }            } catch (NumberFormatException nfe) {                // keep the default            }        }        // Get how long a not in use connection should stay in the pool.        prop = Configuration.getProperty(                   "com.sun.midp.io.http.persistent_connection_linger_time");        if (prop != null) {            try {                temp = Integer.parseInt(prop);                if (temp >= 0) {                    connectionLingerTime = temp;                }            } catch (NumberFormatException nfe) {                // keep the default            }        }        connectionPool = new StreamConnectionPool(                                 maxNumberOfPersistentConnections,                                 connectionLingerTime);        /*         * Get the  maximum number of persistent connections         * from the configuration file.         */        prop = Configuration.getProperty(                            "com.sun.midp.io.http.inputBufferSize");        if (prop != null) {            try {                temp = Integer.parseInt(prop);                if (temp <= 0) {                    inputBufferSize = temp;                }            } catch (NumberFormatException nfe) {                // keep the default            }        }        prop = Configuration.getProperty(                            "com.sun.midp.io.http.outputBufferSize");        if (prop != null) {            try {                temp = Integer.parseInt(prop);                if (temp <= 0) {                    outputBufferSize = temp;                }            } catch (NumberFormatException nfe) {                // keep the default            }        }        outputDataSize = outputBufferSize - HTTP_OUTPUT_DATA_OFFSET -                         HTTP_OUTPUT_EXTRA_ROOM;    }    /**     * Initializes the security token for this class, so it can     * perform actions that a normal MIDlet Suite cannot.     *     * @param token security token for this class.     */    public static void initSecurityToken(SecurityToken token) {        if (classSecurityToken != null) {            return;        }                classSecurityToken = token;    }    /** Saved copy of URL string to be processed. */    protected String saved_url;    /** Default port number for this protocol. */    protected int default_port;    /** Parsed Url. */    protected HttpUrl url;    /** url.host + ":" + url.port. */    protected String hostAndPort;    /** Numeric code returned from HTTP response header. */    protected int responseCode;    /** Message string from HTTP response header. */    protected String responseMsg;    /** Collection of request headers as name/value pairs. */    protected Properties reqProperties;    /** Collection of response headers as name/value pairs. */    protected Properties headerFields;    /** HTTP method type for the current request. */    protected String method;        /*     * The streams from the underlying socket connection.     */    /** Low level socket connection used for the HTTP requests. */    private StreamConnection streamConnection;    /** Low level socket output stream. */    private DataOutputStream streamOutput;    /** Low level socket input stream. */    private DataInputStream streamInput;    /** A shared temporary header buffer. */    private StringBuffer stringbuffer;    /** HTTP version string set with all incoming HTTP responses. */    private String httpVer = null;    /** Used when appl calls setRequestProperty("Connection", "close"). */    private boolean ConnectionCloseFlag;    /** Content-Length from response header, or -1 if missing. */    private int contentLength = -1;    /**     * Total number of bytes in the current chunk or content-length when     * data is sent as one big chunk.     */    private int chunksize = -1;    /**     * Number of bytes read from the stream for non-chunked data or     * the bytes read from the current chunk.     */     private int totalbytesread;    /** True if Transfer-Encoding: chunkedIn. */    private boolean chunkedIn;         /** True if Transfer-Encoding: chunkedOut. */    private boolean chunkedOut;        /** True after the first chunk has been sent. */    private boolean firstChunkSent;    /** True if the request is being sent. */    private boolean sendingRequest;    /** True if the entire request has been sent to the server. */    private boolean requestFinished;    /** True if eof seen. */    private boolean eof;               /** Internal stream buffer to minimize the number of TCP socket reads. */    private byte[] readbuf;             /** Number of bytes left in internal input stream buffer. */    private int bytesleft;    /** Number of bytes read from the internal input stream buffer. */     private int bytesread;         /** Buffered data output for content length calculation. */    private byte[] writebuf;             /** Number of bytes of data that need to be written from the buffer. */    private int bytesToWrite;    /** Collection of "Proxy-" headers as name/value pairs. */    private Properties proxyHeaders = new Properties();    /** Last handshake error. */    private byte handshakeError;    /**     * Holds the state the readBytes call. So if close is called in another     * thread than the read thread the close will be directly on the stream,     * instead of putting the connection back in the persistent connection     * pool, forcing an IOException on the read thread.     */    private boolean readInProgress;    /**     * Create a new instance of this class and intialize variables.     * Initially an http connection is unconnected to the network.     */    public Protocol() {        reqProperties = new Properties();        headerFields = new Properties();        stringbuffer = new StringBuffer(32);        method = GET;        responseCode = -1;        protocol = "http";        default_port = 80;        if (nonPersistentFlag) {            ConnectionCloseFlag = true;        }        readbuf = new byte[inputBufferSize];        requiredPermission = Permissions.HTTP;    }    /**     * Provides the connect() method that sets up the connection, but     * does not actually connect to the server until there's something     * to do.     * <p>     * Warning: A subclass that implements this method, not call this     * method and should also implement the disconnect method.     *     * @param name             The URL for the connection, without the     *                         without the protcol part.     * @param mode             The access mode, ignored     * @param timeouts         A flag to indicate that the called wants     *                         timeout exceptions, ignored     *     * @exception IllegalArgumentException If a parameter is invalid.     * @exception ConnectionNotFoundException If the connection cannot be     *             found.     * @exception IOException  If some other kind of I/O error occurs.     */    protected void connect(String name, int mode, boolean timeouts)        throws IOException, IllegalArgumentException,        ConnectionNotFoundException {        this.saved_url = name;        url = new HttpUrl(protocol, name);        if (url.port == -1) {            url.port = default_port;        }        if (url.host == null) {            throw new IllegalArgumentException("missing host in URL");        }        hostAndPort = url.host + ":" + url.port;    }        /**     * Open the input stream if it has not already been opened.     *     * @exception IOException is thrown if it has already been opened.     * @return input stream for the current connection     */    public InputStream openInputStream() throws IOException {        InputStream in;        /*         * Call into parent to create input stream passed back to the user         */        in = super.openInputStream();               /*         * Send a request to the web server if there wasn't one         * sent already         */        sendRequest();        return in;    }           /**     * Open the output stream if it has not already been opened.     *     * @exception IOException is thrown if it has already been opened.     * @return output stream for the current connection     */    public OutputStream openOutputStream() throws IOException {        OutputStream out;        /*         * call into parent to create output stream passed back to the user         */        out = super.openOutputStream();        /*         * Create a byte array output stream for output buffering         * once the user calls flush() this gets written to stream         */        writebuf = new byte[outputBufferSize];        return out;    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -