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

📄 installer.java

📁 有关j2me的很好的例子可以研究一下
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
     * Download an resource from the given URL into the output stream.     *     * @param url location of the resource to download     * @param extraFieldKeys keys to the extra fields to put in the request     * @param extraFieldValues values to the extra fields to put in the request     * @param acceptableTypes list of acceptable media types for this resource,     *                        there must be at least one     * @param output output stream to write the resource to     * @param encoding an array to receive the character encoding of resource,     *                 can be null     * @param serverNotFoundCode reason code to use when the server is not     *     found     * @param resourceNotFoundCode reason code to use when the resource is not     *     found on the server     * @param invalidMediaTypeCode reason code to use when the media type of     *     the resource is not valid     *     * @return size of the resource     *     * @exception IOException is thrown if any error prevents the download     *   of the resource.     */    private int downloadResource(String url, String[] extraFieldKeys,            String[] extraFieldValues, String[] acceptableTypes,            OutputStream output, String[] encoding,            int serverNotFoundCode, int resourceNotFoundCode,            int invalidMediaTypeCode) throws IOException {        Connection conn = null;        StringBuffer acceptField;        int responseCode;        String retryAfterField;        int retryInterval;        String mediaType;        String temp;        try {            for (; ; ) {                try {                    conn = Connector.open(url, Connector.READ);                } catch (Exception e) {                    throw new InvalidJadException(serverNotFoundCode);                }                if (!(conn instanceof HttpConnection)) {                    throw new InvalidJadException(serverNotFoundCode);                }                httpConnection = (HttpConnection)conn;                if (extraFieldKeys != null) {                     for (int i = 0; i < extraFieldKeys.length &&                            extraFieldKeys[i] != null; i++) {                        httpConnection.setRequestProperty(extraFieldKeys[i],                                                          extraFieldValues[i]);                    }                }                                    // 256 is given to avoid resizing without adding lengths                acceptField = new StringBuffer(256);                // there must be one or more acceptable media types                acceptField.append(acceptableTypes[0]);                for (int i = 1; i < acceptableTypes.length; i++) {                    acceptField.append(", ");                    acceptField.append(acceptableTypes[i]);                }                httpConnection.setRequestProperty("Accept",                                                  acceptField.toString());                httpConnection.setRequestMethod(HttpConnection.GET);                if (state.username != null &&                        state.password != null) {                    httpConnection.setRequestProperty("Authorization",                        formatAuthCredentials(state.username,                                              state.password));                }                if (state.cookie != null) {                    httpConnection.setRequestProperty("Cookie",                        formatReturnCookie(state.cookie));                }                try {                    responseCode = httpConnection.getResponseCode();                } catch (IOException ioe) {                    throw new InvalidJadException(serverNotFoundCode);                }                responseCode = httpConnection.getResponseCode();                if (responseCode != HttpConnection.HTTP_UNAVAILABLE) {                    break;                }                retryAfterField = httpConnection.getHeaderField("Retry-After");                if (retryAfterField == null) {                    break;                }                try {                    /*                     * see if the retry interval is in seconds, and                     * not an absolute date                     */                    retryInterval = Integer.parseInt(retryAfterField);                    if (retryInterval > 0) {                        if (retryInterval > 60) {                            // only wait 1 min                            retryInterval = 60;                        }                        Thread.sleep(retryInterval * 1000);                    }                } catch (InterruptedException ie) {                    // ignore thread interrupt                    break;                } catch (NumberFormatException ne) {                    // ignore bad format                    break;                }                httpConnection.close();                if (state.stopInstallation) {                    postStatusBackToProvider(USER_CANCELLED_MSG);                    throw new IOException("stopped");                }            } // end for            if (responseCode == HttpConnection.HTTP_NOT_FOUND) {                throw new InvalidJadException(resourceNotFoundCode);            }            if (responseCode == HttpConnection.HTTP_NOT_ACCEPTABLE) {                throw new InvalidJadException(invalidMediaTypeCode);            }            if (responseCode == HttpConnection.HTTP_UNAUTHORIZED) {                // automatically throws the correct exception                checkIfBasicAuthSupported(                     httpConnection.getHeaderField("WWW-Authenticate"));                throw new                    InvalidJadException(InvalidJadException.UNAUTHORIZED);            }            if (responseCode != HttpConnection.HTTP_OK) {                throw new IOException("Failed to download " + url +                    " HTTP response code: " + responseCode);            }            mediaType = getMediaType(httpConnection.getType());            if (mediaType != null) {                boolean goodType = false;                for (int i = 0; i < acceptableTypes.length; i++) {                    if (mediaType.equals(acceptableTypes[i])) {                        goodType = true;                        break;                    }                }                if (!goodType) {                    throw new InvalidJadException(invalidMediaTypeCode,                                                  mediaType);                }            }            if (encoding != null) {                encoding[0] = getCharset(httpConnection.getType());            }            temp = httpConnection.getHeaderField("Set-Cookie");            if (temp != null) {                state.cookie = temp;            }            httpInputStream = httpConnection.openInputStream();            return transferData(httpInputStream, output);        } finally {            // Close the streams or connections this method opened.            try {                httpInputStream.close();            } catch (Exception e) {                // ignore            }                                try {                conn.close();            } catch (Exception e) {                // ignore            }        }    }    /**     * Check to make sure the HTTP server will support Basic authtication.     *     * @param wwwAuthField WWW-Authenticate field from the response header     *     * @exception InvalidJadException if server does not support Basic     *                                authentication     */    private void checkIfBasicAuthSupported(String wwwAuthField)             throws InvalidJadException {        wwwAuthField = wwwAuthField.trim();        if (!wwwAuthField.regionMatches(true, 0, BASIC_TAG, 0,                                        BASIC_TAG.length())) {            throw new InvalidJadException(InvalidJadException.CANNOT_AUTH);        }    }    /**     * Parse out the media-type from the content-type field and convert     * to lower case.     * The media-type everything for the ';' that marks the parameters.     *     * @param contentType value of the content-type field     *     * @return media-type in lower case     */    private static String getMediaType(String contentType) {        int semiColon;        if (contentType == null) {            return null;        }        semiColon = contentType.indexOf(';');        if (semiColon < 0) {            return contentType.toLowerCase();        }        return contentType.substring(0, semiColon).toLowerCase();    }    /**     * Parse out the charset from the content-type field.     * The charset parameter is after the ';' in the content-type field.     *     * @param contentType value of the content-type field     *     * @return charset     */    private static String getCharset(String contentType) {        int start;        int end;        if (contentType == null) {            return null;        }        start = contentType.indexOf("charset");        if (start < 0) {            return null;        }        start = contentType.indexOf('=', start);        if (start < 0) {            return null;        }        // start past the '='        start++;        end = contentType.indexOf(';', start);        if (end < 0) {            end = contentType.length();        }                    return contentType.substring(start, end).trim();    }    /**     * Format the username and password for HTTP basic authentication     * according RFC 2617.     *     * @param username for HTTP authentication     * @param password for HTTP authentication     *     * @return properly formated basic authentication credential     */    private static String formatAuthCredentials(String username,                                                String password) {        byte[] data = new byte[username.length() + password.length() + 1];        int j = 0;        for (int i = 0; i < username.length(); i++, j++) {            data[j] = (byte)username.charAt(i);        }        data[j] = (byte)':';        j++;        for (int i = 0; i < password.length(); i++, j++) {            data[j] = (byte)password.charAt(i);        }        return "Basic " + Base64.encode(data, 0, data.length);    }    /**     * Format the cookie to be returned to the HTTP server     * according to RFC 2109.     *     * @param cookieField Set-Cookie field from the response header     *     * @return Cookie field to send back to the server     */    String formatReturnCookie(String cookieField) {        Vector params = new Vector();        int i;        char currentChar;        String param;        int start = 0;        StringBuffer cookie;        String version = null;        String domain = null;        String path = null;                try {            /*             * get the parameters from only the first cookie,             * so upto the first ","             */            for (i = 0; i < cookieField.length(); i++) {                currentChar = cookieField.charAt(i);                if (currentChar == ',') {                    break;                }                // parameters are separated by a ";" and can have white space                if (currentChar == ';') {                    params.addElement(cookieField.substring(start, i).trim());                    start = i + 1;                }            }            params.addElement(cookieField.substring(start, i).trim());            cookie = new StringBuffer((String)params.elementAt(0));            for (i = 1; i < params.size(); i++) {                param = (String)params.elementAt(i);                if (param.regionMatches(true, 0, VERSION_TAG, 0,                                        VERSION_TAG.length())) {                    version = param;                    continue;                }                if (param.regionMatches(true, 0, DOMAIN_TAG, 0,                                        DOMAIN_TAG.length())) {                    domain = param;                }                if (param.regionMatches(true, 0, PATH_TAG, 0,                                        PATH_TAG.length())) {                    path = param;                }            }                } finally {}        cookie.append(";$");        cookie.append(version);        if (domain != null) {            cookie.append(";$");            cookie.append(domain);        }        if (path != null) {            cookie.append(";$");

⌨️ 快捷键说明

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