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

📄 protocol.java

📁 已经移植好的java虚拟机
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        }        this.method = new String(method);    }    public String getRequestProperty(String key) {        return (String)reqProperties.get(key);    }    public void setRequestProperty(String key, String value)        throws IOException {        if (connected) {            throw new IOException("connection already open");        }        reqProperties.put(key, value);    }    public int getResponseCode() throws IOException {        connect();        return responseCode;    }    public String getResponseMessage() throws IOException {        connect();        return responseMsg;    }    public long getLength() {        try {            connect();        }        catch (IOException x) {            return -1;        }        return getHeaderFieldInt("content-length", -1);    }    public String getType() {        try {            connect();        }        catch (IOException x) {            return null;        }        return getHeaderField("content-type");    }    public String getEncoding() {        try {            connect();        }        catch (IOException x) {            return null;        }        return getHeaderField("content-encoding");    }    public long getExpiration() {        return getHeaderFieldDate("expires", 0);    }    public long getDate() {        return getHeaderFieldDate("date", 0);    }    public long getLastModified() {        return getHeaderFieldDate("last-modified", 0);    }    public String getHeaderField(String name) {        try {            connect();        }        catch (IOException x) {            return null;        }        return (String)headerFields.get(toLowerCase(name));    }    public String getHeaderField(int index) {        try {            connect();        }        catch (IOException x) {            return null;        }        if (headerFieldValues == null) {            makeHeaderFieldValues ();        }        if (index >= headerFieldValues.length)            return null;        return headerFieldValues[index];    }    public String getHeaderFieldKey(int index) {        try {            connect();        }        catch (IOException x) {            return null;        }        if (headerFieldNames == null) {            makeHeaderFields ();        }        if (index >= headerFieldNames.length) {            return null;        }        return headerFieldNames[index];    }    private void makeHeaderFields() {        int i = 0;        headerFieldNames = new String[headerFields.size()];        for (Enumeration e = headerFields.keys();            e.hasMoreElements();            headerFieldNames[i++] = (String)e.nextElement());    }    private void makeHeaderFieldValues() {        int i = 0;        headerFieldValues = new String[headerFields.size()];        for (Enumeration e = headerFields.keys();             e.hasMoreElements();             headerFieldValues[i++]=(String)headerFields.get(e.nextElement()));    }    public int getHeaderFieldInt(String name, int def) {        try {            connect();        }        catch (IOException x) {            return def;        }        try {            return Integer.parseInt(getHeaderField(name));        } catch(Throwable t) {}        return def;    }    public long getHeaderFieldDate(String name, long def) {        try {            connect();        }        catch (IOException x) {            return def;        }        try {            return DateParser.parse(getHeaderField(name));        } catch(Throwable t) {}        return def;    }    protected void connect() throws IOException {System.out.println("Connect");        if (connected) return;        // Open socket connection        streamConnnection =            (StreamConnection)Connector.open("socket://"+host+":"+port);        // Open data output stream        streamOutput = streamConnnection.openDataOutputStream();        // HTTP 1.1 requests must contain content length for proxies        if (getRequestProperty("Content-Length") == null) {            setRequestProperty("Content-Length",                "" + (out == null ? 0 : out.size()));        }        String reqLine = method + " " + getFile()            + (getRef() == null ? "" : "#" + getRef())            + (getQuery() == null ? "" : "?" + getQuery())            + " " + http_version + "\r\n";        streamOutput.write((reqLine).getBytes());        // HTTP 1/1 requests require the Host header to        // distinguish virtual host locations.        setRequestProperty ("Host" ,  host + ":" + port );        Enumeration reqKeys = reqProperties.keys();        while (reqKeys.hasMoreElements()) {            String key = (String)reqKeys.nextElement();            String reqPropLine = key + ": " + reqProperties.get(key) + "\r\n";            streamOutput.write((reqPropLine).getBytes());        }        streamOutput.write("\r\n".getBytes());        if (out != null) {            streamOutput.write(out.toByteArray());            //***Bug 4485901*** streamOutput.write("\r\n".getBytes());        }        streamOutput.flush();        streamInput = streamConnnection.openDataInputStream();        readResponseMessage(streamInput);        readHeaders(streamInput);        // Ignore a continuation header and read the true headers again.        // (Bug# 4382226 discovered with Jetty HTTP 1.1 web server.        if (responseCode == 100 ) {            readResponseMessage(streamInput);            readHeaders(streamInput);        }        connected = true;    }    private void readResponseMessage(InputStream in) throws IOException {        String line = readLine(in);        int httpEnd, codeEnd;        responseCode = -1;        responseMsg = null;        malformed: {            if (line == null)                break malformed;            httpEnd = line.indexOf(' ');            if (httpEnd < 0)                break malformed;            String httpVer = line.substring(0, httpEnd);            if (!httpVer.startsWith("HTTP"))                break malformed;            if (line.length() <= httpEnd)                break malformed;            codeEnd = line.substring(httpEnd + 1).indexOf(' ');            if (codeEnd < 0)                break malformed;            codeEnd += (httpEnd + 1);            if (line.length() <= codeEnd)                break malformed;            try {                responseCode =                    Integer.parseInt(line.substring(httpEnd + 1, codeEnd));            }            catch (NumberFormatException nfe) {                break malformed;            }            responseMsg = line.substring(codeEnd + 1);            return;        }        throw new IOException("malformed response message");    }    private void readHeaders(InputStream in) throws IOException {        String line, key, value;        int index;        for (;;) {            line = readLine(in);            if (line == null || line.equals(""))                return;            index = line.indexOf(':');            if (index < 0)                throw new IOException("malformed header field");            key = line.substring(0, index);            if (key.length() == 0)                throw new IOException("malformed header field");            if (line.length() <= index + 2) {                value = "";            } else {                value = line.substring(index + 2);            }            headerFields.put(toLowerCase(key), value);        }    }    /*     * Uses the shared stringbuffer to read a line     * terminated by <cr><lf> and return it as string.     */    private String readLine(InputStream in) {        int c;        stringbuffer.setLength(0);        for (;;) {            try {                c = in.read();                if (c < 0) {                    return null;                }                if (c == '\r') {                    continue;                }            } catch (IOException ioe) {                return null;            }            if (c == '\n') {                break;            }            stringbuffer.append((char)c);        }        return stringbuffer.toString();    }    protected void disconnect() throws IOException {        if (streamConnnection != null) {            streamInput.close();            streamOutput.close();            streamConnnection.close();            streamConnnection = null;        }        responseCode = -1;        responseMsg = null;        connected = false;    }    private String parseProtocol() throws IOException {        int n = url.indexOf(':');        if (n <= 0) {            throw new IOException("malformed URL");        }        String token = url.substring(0, n);        if (!token.equals("http")) {            throw new IOException("protocol must be 'http'");        }        index = n + 1;        return token;    }    private String parseHostname() throws IOException {        String buf = url.substring(index);        if (buf.startsWith("//")) {            buf = buf.substring(2);            index += 2;        }    int n = buf.indexOf(':');        if (n < 0) n = buf.indexOf('/');        if (n < 0) n = buf.length();        String token = buf.substring(0, n);        index += n;        return token;    }    private int parsePort() throws IOException {        int p = 80;        String buf = url.substring(index);        if (!buf.startsWith(":")) return p;        buf = buf.substring(1);        index++;        int n = buf.indexOf('/');        if (n < 0) n = buf.length();        try {            p = Integer.parseInt(buf.substring(0, n));            if (p <= 0) {                throw new NumberFormatException();            }        } catch (NumberFormatException nfe) {            throw new IOException("invalid port");        }        index += n;        return p;    }    private String parseFile() throws IOException {        String token = "";        String buf = url.substring(index);        if (buf.length() == 0) return token;        if (!buf.startsWith("/")) {            throw new IOException("invalid path");        }        int n = buf.indexOf('#');        int m = buf.indexOf('?');        if (n < 0 && m < 0) {            n = buf.length(); // URL does not contain any query or frag id.        } else if (n < 0 || (m > 0 && m < n)) {            n = m ;           // Use query loc if no frag id is present                              // or if query comes before frag id.                              // otherwise just strip the frag id.        }        token = buf.substring(0, n);        index += n;        return token;    }    private String parseRef() throws IOException {        String buf = url.substring(index);        if (buf.length() == 0 || buf.charAt(0) == '?') return "";        if (!buf.startsWith("#")) {            throw new IOException("invalid ref");        }        int n = buf.indexOf('?');        if (n < 0) n = buf.length();        index += n;        return buf.substring(1, n);    }    private String parseQuery() throws IOException {        String buf = url.substring(index);        if (buf.length() == 0) return "";        if (buf.startsWith("?")) {            String token = buf.substring(1);            int n = buf.indexOf('#');            if (n > 0) {                token = buf.substring(1, n);                index += n;            }            return token;        }        return "";    }    protected synchronized void parseURL() throws IOException {        index = 0;        host = parseHostname();        port = parsePort();        file = parseFile();        query = parseQuery();        ref = parseRef();    }    private String toLowerCase(String string) {        // Uses the shared stringbuffer to create a lower case string.        stringbuffer.setLength(0);        for (int i=0; i<string.length(); i++) {            stringbuffer.append(Character.toLowerCase(string.charAt(i)));        }        return stringbuffer.toString();    }}

⌨️ 快捷键说明

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