服務器到客戶端:
下面代碼是服務器端把字符寫到Client端,經過gbEncoding()方法,所有的字符編碼成:\uXXXX.
代碼:
/**
* Write the String data
*
* @param out
* @param value
*/
public static void writeUnicode(final DataOutputStream out, final String value)
throws ActionException {
try {
final String unicode = StringFormatter.gbEncoding( value );
final byte[] data = unicode.getBytes();
final int dataLength = data.length;
System.out.println( "Data Length is: " + dataLength );
System.out.println( "Data is: " + value );
out.writeInt( dataLength );
out.write( data, 0, dataLength );
} catch (IOException e) {
throw new ActionException( IMDefaultAction.class.getName(), e.getMessage() );
}
}
以下代碼是gbEncoding()方法,把雙字節字符轉換成\uXXXX,ASIIC碼在前面補00。
代碼:
/**
* This method will encode the String to unicode.
*
* @param gbString
* @return
*/
public static String gbEncoding( final String gbString ) {
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for( int byteIndex = 0; byteIndex < utfBytes.length; byteIndex ++ ) {
String hexB = Integer.toHexString( utfBytes[ byteIndex ] );
if( hexB.length() <= 2 ) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "u" + hexB;
}
System.out.println( "unicodeBytes is: " + unicodeBytes );
return unicodeBytes;
}
在客戶端收到服務器的數據,先將其一個一個字符解碼。雙字節顯示正常。
代碼:
**
* This method will decode the String to a recognized String
* in ui.
* @param dataStr
* @return
*/
private StringBuffer decodeUnicode( final String dataStr ) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while( start > -1 ) {
end = dataStr.indexOf( "u", start + 2 );
String charStr = "";
if( end == -1 ) {
charStr = dataStr.substring( start + 2, dataStr.length() );
} else {
charStr = dataStr.substring( start + 2, end);
}
char letter = (char) Integer.parseInt( charStr, 16 ); // 16進制parse整形字符串。
buffer.append( new Character( letter ).toString() );
start = end;
}
return buffer;
}
客戶端到服務器:
客戶端使用下面方法把手機端的字符編碼成ISO-8859-1,傳給服務器。
代碼:
/**
* write the String data
* @param value
* @param outData
*/
private void writeSjis(DataOutputStream outData, String value) {
try {
byte[] data = null;
// data = ( value ).getBytes( "UTF-8" );
data = ( value ).getBytes( "ISO8859_1" );
outData.writeInt(data.length);
outData.write(data, 0, data.length);
System.out.println(" data.length: " + data.length);
System.out.println(" data.value: " + value);
} catch (Exception ex) {
System.out.println(" write error ");
ex.printStackTrace();
}
}
服務器端收到客戶端字符流,是用下面方法將其轉為UTF-8,以後的操作都是基於UTF-8編碼。SQLServer可能會由於內嗎不通有不同的變換,所以存取數據庫是還要是具體的DB內碼作相應的處理。
代碼:
/**
*
* @param iso
* @return
*/
public static String isoToUtf( final String iso ) {
String utfString = iso;
if( iso != null ) {
try {
utfString = new String( iso.getBytes( "ISO-8859-1" ), "UTF-8" );
} catch ( UnsupportedEncodingException e ) {
utfString = iso;
}
} else {
utfString = "";
}
return utfString;
}
注:
本方法應該不是最有效的,但是只要手機支持unicode的gb2312編碼,應該都可以顯示正常。