J2ME 網絡訪問 亂碼問題

根本的解決思路是比較不同環境中編碼的最終編碼字符串,可以使用字節流或者字符流。

服務器: ASP.NET2.0 IIS7
客戶端:J2ME

J2ME提交數據到服務器:

提交之前使用URLEcode進行HTML編碼;
HTML 格式編碼的實用工具類。該類包含了將 String 轉換爲 application/x-www-form-urlencoded MIME 格式的靜態方法。
具體詳見:
http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/net/URLEncoder.html

服務端使用:Server.UrlDecode(url);

服務端傳字符到J2ME:

服務端使用UTF-8編碼
手機客戶端使用:new String(str.getBytes("ISO8859_1"), "UTF-8");

下邊是URLEncode工具類
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class URLEncoder {
   
    /** The characters which do not need to be encoded. */
    private static boolean[] dontNeedEncoding;
    private static String defaultEncName = "";
    static final int caseDiff = ('a' - 'A');
    static {
        dontNeedEncoding = new boolean[256];
        int i;
        for (i = 'a'; i <= 'z'; i++) {
            dontNeedEncoding[i] = true;
        }
        for (i = 'A'; i <= 'Z'; i++) {
            dontNeedEncoding[i] = true;
        }
        for (i = '0'; i <= '9'; i++) {
            dontNeedEncoding[i] = true;
        }
        dontNeedEncoding[' '] = true; // encoding a space to a + is done in the encode() method
        dontNeedEncoding['-'] = true;
        dontNeedEncoding['_'] = true;
        dontNeedEncoding['.'] = true;
        dontNeedEncoding['*'] = true;
        defaultEncName = System.getProperty("microedition.encoding");
        if(defaultEncName == null || defaultEncName.trim().length() == 0){
            defaultEncName = "UTF-8";
        }
        System.out.println("system encode:"+defaultEncName);
    }
   
    public static final int MIN_RADIX = 2;
   
    /**
     * The maximum radix available for conversion to and from strings.
     */
    public static final int MAX_RADIX = 36;
    /**
     * The class is not meant to be instantiated.
     */
    private URLEncoder() { }
   
   
    /**
     * Translates a string into "<CODE>x-www-form-urlencoded</CODE>"
     * format.This method uses the platform's default encoding
     * as the encoding scheme to obtain the bytes for unsafe characters.
     *
     * @param  s the string to be translated.
     *
     * @return The resulting string.
     */
    public static String encode(String s) {
        String str = null;
        str = encode(s, defaultEncName);
        return str;
    }
       /**
     * Translates a string into <code>application/x-www-form-urlencoded</code>
     * format using a specific encoding scheme. This method uses the
     * supplied encoding scheme to obtain the bytes for unsafe
     * characters.
     * <p>
     * <em><strong>Note:</strong> The <a href=
     * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
     * World Wide Web Consortium Recommendation</a> states that
     * UTF-8 should be used. Not doing so may introduce
     * incompatibilites.</em>
     *
     * @param   s   <code>String</code> to be translated.
     * @param   enc   The name of a supported character encoding such as UTF-8
     * @return  the translated <code>String</code>.
     */
    public static String encode(String s, String enc) {
       
        boolean needToChange = false;
        boolean wroteUnencodedChar = false;
        int maxBytesPerChar = 10; // rather arbitrary limit, but safe for now
        StringBuffer out = new StringBuffer(s.length());
        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
        OutputStreamWriter writer = null;
        try {
            writer = new OutputStreamWriter(buf, enc);
        } catch (UnsupportedEncodingException ex) {
            try {
                writer = new OutputStreamWriter(buf,defaultEncName);
            } catch (UnsupportedEncodingException e) {
                //never reach
            }
        }
       
        for (int i = 0; i < s.length(); i++) {
            int c = (int) s.charAt(i);
            //System.out.println("Examining character: " + c);
            if (c <256 && dontNeedEncoding[c]) {
                if (c == ' ') {
                    c = '+';
                    needToChange = true;
                }
                //System.out.println("Storing: " + c);
                out.append((char)c);
                wroteUnencodedChar = true;
            } else {
                // convert to external encoding before hex conversion
                try {
                    if (wroteUnencodedChar) { // Fix for 4407610
                        writer = new OutputStreamWriter(buf, enc);
                        wroteUnencodedChar = false;
                    }
                    if(writer != null)
                        writer.write(c);
                    /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                    if (c >= 0xD800 && c <= 0xDBFF) {
                        /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                         */
                        if ( (i+1) < s.length()) {
                            int d = (int) s.charAt(i+1);
                            /*
                              System.out.println("/tExamining "
                              + Integer.toHexString(d));
                             */
                            if (d >= 0xDC00 && d <= 0xDFFF) {
                                /*
                                  System.out.println("/t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                 */
                                writer.write(d);
                                i++;
                            }
                        }
                    }
                    writer.flush();
                } catch(IOException e) {
                    buf.reset();
                    continue;
                }
                byte[] ba = buf.toByteArray();
                for (int j = 0; j < ba.length; j++) {
                    out.append('%');
                    char ch = forDigit((ba[j] >> 4) & 0xF, 16);
                    if (isLetter(ch)) {
                        ch -= caseDiff;
                 }
                    out.append(ch);
                  
                  ch = forDigit((ba[j] & 0xF), 16);
                   //ch = forDigit(ba[j] & 0xF, 16);
                    if (isLetter(ch)) {
                        ch -= caseDiff;
                    }
                    out.append(ch);
                }
                buf.reset();
                needToChange = true;
            }
        }
       
        return (needToChange? out.toString() : s);
    }
   
    private static boolean isLetter(char c){
        if( (c >= 'a' && c <= 'z') || (c >='A' && c <= 'Z'))
            return true;
        return false;
    }
   
    private static char forDigit(int digit,int radix){
        if ((digit >= radix) || (digit < 0)) {
            return '/0';        }
        if ((radix < MIN_RADIX) || (radix > MAX_RADIX)) {
            return '/0';
        }
        if (digit < 10) {
            return (char)('0' + digit);
        }
        return (char)('a' - 10 + digit);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章