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

📄 httpview.java

📁 j2me Demos for example
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
                String helpString =                    "Use Head, Get or Post to download a URL.\n\n" +                    "Use 'New URL' to enter a new URL.";                Alert alert = new Alert(null, helpString, null, null);                alert.setTimeout(Alert.FOREVER);                display.setCurrent(alert);            }        } catch (Exception ex) {            ex.printStackTrace();        }    }    /**     * Fetch the specified url in a separate thread and update the     * progress bar as it goes.     * If the user cancels the fetch, the thread be changed from this thread.     * If this happens no further updates should be made to the     * displayable forms. Those shared objects may be re-used     * by the next fetch.     */    public void run() {        long start = 0;        long end = 0;        int bytecode_count_start = 0;        int bytecode_count_end = 0;        Thread mythread = Thread.currentThread();        String method = HttpConnection.GET;        if (requestCommand == headCommand) {            method = HttpConnection.HEAD;        } else if (requestCommand == postCommand) {            method = HttpConnection.POST;        }        if (content == null) {            content = new TextBox("Content", "", 4096, 0);            content.addCommand(backCommand);            content.addCommand(headersCommand);            content.setCommandListener(this);        }        // Clear the buffers and forms so then can be displayed        // even if an exception terminates reading early.        content.setTitle("Body len = 0");        content.setString("");        genErrorsForm("Errors", null);        clearForm(requestForm);        clearForm(headerForm);        progressGauge.setValue(1);        HttpConnection conn = null;        InputStream input = null;        OutputStream output = null;        StringBuffer b;        String string = null;        try {            long len = 0;            conn = (HttpConnection)Connector.open(url);            conn.setRequestMethod(method);            setConfig(conn);            if (mythread != thread) {                return;            }            progressGauge.setValue(2);            for (int hops = 0; hops < 2; hops++) {                // Send data to the server (if necessary). Then, see if                // we're redirected. If so, hop to the new URL                // specified by the server.                //                // You can choose how many hops to make by changing the                // exit condition of this loop.                //                // To see an example of this, try the link                // "http://www.sun.com/products" link, which will                // redirect you to a link with a session ID.                if (method == HttpConnection.POST) {                    output = conn.openOutputStream();                    if (mythread != thread) {                        return;                    }                    output.write("hello midlet world".getBytes());                    output.close();                    output = null;                }                HttpConnection newConn = handleRedirects(conn);                if (conn != newConn) {                    conn = newConn;                } else {                    break;                }            }            genRequestForm(conn);            input = conn.openInputStream();            if (mythread != thread) {                return;            }            content.setTitle(conn.getResponseMessage() + " (" + conn.getResponseCode() + ")");            genHeaderForm(conn);            progressGauge.setValue(5);            if (mythread != thread) {                return;            }            // Download the content of the URL. We limit our download            // to 4096 bytes (content.getMaxSize()), as most small            // devices may not be able to handler larger size.            //            // A "real program", of course, needs to handle large            // downloads intelligently. If possible, it should work            // with the server to limit downloads to small sizes. If            // this is not possible, it should download only part of            // the data and allow the user to specify which part to            // download.            len = conn.getLength();            b = new StringBuffer((len >= 0) ? (int)len : 1000);            int max = content.getMaxSize();            if (len != -1) {                // Read content-Length bytes, or until max is reached.                int ch = 0;                for (int i = 0; i < len; i++) {                    if ((ch = input.read()) != -1) {                        if (ch <= ' ') {                            ch = ' ';                        }                        b.append((char)ch);                        if (b.length() >= max) {                            break;                        }                    }                }            } else {                // Read til the connection is closed, or til max is reached.                // (Typical HTTP/1.0 script generated output)                int ch = 0;                len = 0;                while ((ch = input.read()) != -1) {                    if (ch <= ' ') {                        ch = ' ';                    }                    b.append((char)ch);                    if (b.length() >= max) {                        break;                    }                }            }            string = b.toString();            if (mythread != thread) {                return;            }            progressGauge.setValue(8);            content.setTitle("Body len = " + b.length());            if (b.length() > 0) {                content.setString(string);            } else {                content.setString("no data");            }            display.setCurrent(content);            progressGauge.setValue(9);        } catch (OutOfMemoryError mem) {            // Mmm, we still run out of memory, even after setting            // max download to 4096 bytes. Tell user about the error.            //            // A "real program" should decide on the max download            // size depending on available heap space, or perhaps            // allow the user to set the max size            b = null;            content = null; // free memory to print error            mem.printStackTrace();            if (mythread != thread) {                genErrorsForm("Memory", mem);                display.setCurrent(errorsForm);            }        } catch (Exception ex) {            ex.printStackTrace();            genErrorsForm("Errors", ex);            display.setCurrent(errorsForm);        } finally {            cleanUp(conn, input, output);            if (mythread == thread) {                progressGauge.setValue(10);            }        }    }    /**     * Clean up all objects used by the HttpConnection. We must     * close the InputStream, OutputStream objects, as well as the     * HttpConnection object, to reclaim system resources. Otherwise,     * we may not be able to make new connections on some platforms.     *     * @param conn the HttpConnection     * @param input the InputStream of the HttpConnection, may be null     *              if it's not yet opened.     * @param output the OutputStream the HttpConnection, may be null     *              if it's not yet opened.     */    void cleanUp(HttpConnection conn, InputStream input, OutputStream output) {        Thread mythread = Thread.currentThread();        try {            if (input != null) {                input.close();            }        } catch (IOException e) {            if (mythread == thread) {                genErrorsForm("InputStream close error", e);            }        }        try {            if (output != null) {                output.close();            }        } catch (IOException e) {            if (mythread == thread) {                genErrorsForm("OutStream close error", e);            }        }        try {            if (conn != null) {                conn.close();            }        } catch (IOException e) {            if (mythread == thread) {                genErrorsForm("HttpConnection close error", e);            }        }    }    /**     * Check for redirect response codes and handle     * the redirect by getting the new location and     * opening a new connection to it.  The original     * connection is closed.     * The process repeats until there are no more redirects.     * @param c the initial HttpConnection     * @return the final HttpConnection     */    HttpConnection handleRedirects(HttpConnection c) throws IOException {        while (true) {            int code = c.getResponseCode();            switch (code) {            case HttpConnection.HTTP_TEMP_REDIRECT:            case HttpConnection.HTTP_MOVED_TEMP:            case HttpConnection.HTTP_MOVED_PERM:                String loc = c.getHeaderField("location");                c.close();                showAlert("Redirecting to " + loc, null);                progressGauge.setLabel(loc);                c = (HttpConnection)Connector.open(loc);                continue;            default:                return c;            }        }    }    /**     * Add request properties for the configuration, profiles,     * and locale of this system.     * @param c current HttpConnection to receive user agent header     */    void setConfig(HttpConnection c) throws IOException {        String conf = System.getProperty("microedition.configuration");        String prof = System.getProperty("microedition.profiles");        int space = prof.indexOf(' ');        if (space != -1) {            prof = prof.substring(0, space - 1);        }        String platform = System.getProperty("microedition.platform");        String locale = System.getProperty("microedition.locale");        String ua = "Profile/" + prof + " Configuration/" + conf + " Platform/" + platform;        c.setRequestProperty("User-Agent", ua);        if (locale != null) {            c.setRequestProperty("Content-Language", locale);        }    }    /**     * Generate and fill in the Form with the header fields.     * @param c the open connection with the result headers.     */    void genHeaderForm(HttpConnection c) throws IOException {        clearForm(headerForm);        headerForm.append(new StringItem("response message: ", c.getResponseMessage()));        headerForm.append(new StringItem("response code: ", c.getResponseCode() + ""));        for (int i = 0;; i++) {            String key = c.getHeaderFieldKey(i);            if (key == null) {                break;            }            String value = c.getHeaderField(i);            StringItem item = new StringItem(key + ": ", value);            headerForm.append(item);        }    }    /**     * Generate the form with the request attributes and values.     * @param c the open connection with the request headers.     */    void genRequestForm(HttpConnection c) throws IOException {        clearForm(requestForm);        requestForm.append(new StringItem("URL: ", c.getURL()));        requestForm.append(new StringItem("Method: ", c.getRequestMethod()));        requestForm.append(new StringItem("Protocol: ", c.getProtocol()));        requestForm.append(new StringItem("Host: ", c.getHost()));        requestForm.append(new StringItem("File: ", c.getFile()));        requestForm.append(new StringItem("Ref: ", c.getRef()));        requestForm.append(new StringItem("Query: ", c.getQuery()));        requestForm.append(new StringItem("Port: ", Integer.toString(c.getPort())));        requestForm.append(new StringItem("User-Agent: ", c.getRequestProperty("User-Agent")));        requestForm.append(new StringItem("Content-Language: ",                c.getRequestProperty("Content-Language")));    }    /**     * Generate the options form with URL title and progress gauge.     * @param name the title of the URL to be loaded.     * @param url label for the progress gauge     */    void genProgressForm(String name, String url) {        progressGauge.setValue(0);        progressGauge.setLabel(url);        progressForm.setTitle(name);    }    /**     * Set the Alert to the exception message and display it.     * @param s the Exception title string     * @param ex the Exception     */    void genErrorsForm(String s, Throwable ex) {        clearForm(errorsForm);        if (s != null) {            errorsForm.setTitle(s);        } else {            errorsForm.setTitle("Exception");        }        if (ex != null) {            ex.printStackTrace();             errorsForm.append(ex.getClass().getName());            errorsForm.append("\n");            String m = ex.getMessage();            if (m != null) {                errorsForm.append(m);            }        } else {            errorsForm.append("None");        }    }    /**     * Set the alert string and display it.     * @param s the error message     * @param next the screen to be shown after the Alert.     */    void showAlert(String s, Screen next) {        alert.setString(s);        if (next == null) {            display.setCurrent(alert);        } else {            display.setCurrent(alert, next);        }    }    /**     * Clear out all items in a Form.     * @param form the Form to clear.     */    void clearForm(Form form) {        int s = form.size();        for (int i = s - 1; i >= 0; i--) {            form.delete(i);        }    }}

⌨️ 快捷键说明

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