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

📄 httpcommunicationhandler.java

📁 实现了一个基于j2me移动gps定位系统
💻 JAVA
📖 第 1 页 / 共 3 页
字号:

                results = readStringContent(connection);
                internalCache.put(serviceURL, results);
            } catch (IOException ioe) {
                ioe.printStackTrace();
                throw new ApplicationException(ioe);
            }
        }
        // Do not close input stream now
        // finally {
        // closeGETConnection(connection, inputStream);
        // }
        return results;
    }

    private String replace(String source, char oldChar, String dest) {

        String ret = "";
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) != oldChar) {
                ret += source.charAt(i);
            } else {
                ret += dest;
            }
        }
        return ret;
    }

    private String toUTF8(String s) {
        s = s.trim();
        try {
            byte[] bytes = s.getBytes("ISO-8859-1");
            return new String(bytes, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println("*********** Unsupported Encoding!");
            return s;
        }
    }

    private String encodeURL(String URL) {
        URL = replace(URL, '\u00e0', "%E0");
        URL = replace(URL, '\u00e8', "%E8");
        URL = replace(URL, '\u00e9', "%E9");
        URL = replace(URL, '\u00ec', "%EC");
        URL = replace(URL, '\u00f2', "%F2");
        URL = replace(URL, '\u00f9', "%F9");
        URL = replace(URL, '\u0024', "%24");
        URL = replace(URL, '\u0023', "%23");
        URL = replace(URL, '\u00a3', "%A3");
        URL = replace(URL, '\u0040', "%40");
        URL = replace(URL, '\'', "%27");
        URL = replace(URL, '\u0020', "%20");

        return URL;
    }

    private HttpConnection openGETConnection(String serverURL)
            throws IOException, CertificateException {
        try {
            HttpConnection connection;
            serverURL = encodeURL(serverURL.trim());

            System.out.println("********** GET serverURL: " + serverURL);

            connection = (HttpConnection) Connector.open(serverURL);

            String userAgent = System.getProperty("microedition.profiles");

            if (userAgent != null && !"".equals(userAgent)) {
                connection.setRequestProperty("User-Agent", userAgent);
            }

            connection.setRequestProperty("Accept-Encoding", "gzip");

            if (0 == serverURL.indexOf("https://")) {
                if (null != credentials && !"".equals(credentials)) {
                    connection.setRequestProperty("Authorization", "Basic "
                            + credentials);
                }
                // connection.setRequestMethod(HttpConnection.POST);
                connection.setRequestMethod(HttpConnection.GET);

                // SecurityInfo si = ((HttpsConnection) connection)
                // .getSecurityInfo();
                // Certificate c = si.getServerCertificate();
                // String subject = c.getSubject();
                // String cipherSuite = si.getCipherSuite();
                //
                // System.out.println("Server certificate subject: \n" +
                // subject);
                //
                // System.out.println("Server Cipher Suite: \n" + cipherSuite);
            } else {
                connection.setRequestMethod(HttpConnection.GET);
            }

            return connection;
        } catch (CertificateException certe) {
            throw certe;
        } catch (IOException ioe) {
            throw ioe;
        }
    }

    private InputStream openConnectionInputStream(HttpConnection connection)
            throws IOException, CertificateException, ApplicationException {
        InputStream inputStream = null;
        int responseCode = connection.getResponseCode();
        try {
            String reponseMessage = connection.getResponseMessage();

            if (responseCode == HttpConnection.HTTP_OK
                    || responseCode == HttpConnection.HTTP_CREATED) {
                inputStream = connection.openInputStream();
                // try {
                // totalData +=
                // Integer.parseInt(connection.getHeaderField("Content-Length"
                // ));
                // }catch(NumberFormatException nfe) {
                // }

                if (null == inputStream) {
                    throw new ApplicationException(
                            MessageCodes.ERROR_CANNOT_CONNECT);
                }

                if ((connection.getEncoding() != null)
                        && (connection.getHeaderField("Content-Encoding")
                                .toLowerCase().indexOf("gzip") != -1)) {
                    inputStream = new GZIPInputStream(inputStream);
                }

                return inputStream;
            } else if (responseCode == HttpConnection.HTTP_UNAUTHORIZED) {
                // missing credentials when server requires
                // them, or credentials sent but invalid
                wwwAuthenticate = connection.getHeaderField("WWW-Authenticate");
                // System.out.println("*********** WWW-Authenticate: "
                // + wwwAuthenticate);
                // closeConnection(connection, inputStream);
                throw new ApplicationException(MessageCodes.ERROR_UNAUTHORIZED);
                // open again, this time with credentials
            } else {
                // System.out.println(" ******* Response Code = " +
                // responseCode);
                // throw new
                // ApplicationException(ioe);
                throw new ApplicationException("HTTP_"
                        + String.valueOf(responseCode) + ": " + reponseMessage);
            }
        } catch (CertificateException certe) {
            throw new ApplicationException(MessageCodes.ERROR_CERTIFICATE);
        } catch (IOException ioe) {
            throw ioe;
        } // finally {
        // closeConnection(connection, inputStream);
        // }
    }

    private String readStringContent(HttpConnection connection)
            throws ApplicationException {
        InputStream inputStream = null;
        boolean isUTF8 = false;
        try {
            if (connection.getResponseCode() == HttpConnection.HTTP_NO_CONTENT) {
                return "";
            }

            if ("UTF-8".equals(connection.getEncoding())
                    || "UTF-8".equals(connection
                            .getHeaderField("Content-Encoding"))) {
                isUTF8 = true;
            }

            updateProgress();
            // Try to free-up memory first
            System.gc();

            StringBuffer resultBuf = new StringBuffer();

            inputStream = openConnectionInputStream(connection);
            updateProgress();
            // long length = connection.getLength();

            int ch;
            // int i = 0;
            while ((ch = inputStream.read()) != -1) {
                resultBuf.append((char) ch);
                totalData++;
                // i++;
                // if (i > (length / 5)) {
                // updateProgress();
                // i = 0;
                // }
            }

            if (isUTF8) {
                return toUTF8(resultBuf.toString());
            } else {
                return resultBuf.toString().trim();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw new ApplicationException(ioe);
        } finally {
            closeConnection(connection, inputStream);
        }
    }

    private void closeConnection(HttpConnection connection,
            InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException ioe) {
            } // Ignored
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (IOException ioe) {
            } // Ignored
        }
    }

    /**
     * @return
     * @uml.property name="wwwAuthenticate"
     */
    public String getWwwAuthenticate() {
        return wwwAuthenticate;
    }

    /**
     * @param credentials
     * @uml.property name="credentials"
     */
    public void setCredentials(String credentials) {
        this.credentials = credentials;
    }

    /**
     * @return the totalData
     */
    public String getTotalData() {
        if (totalData >= 1024) {
            Float f = new Float(totalData);
            f = Float.round(f.Div(1024), 2);

            return String.valueOf(f) + " KB";
        }

        return String.valueOf(totalData) + " B";
    }
}

⌨️ 快捷键说明

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