| |
服务器到客户端:
下面代码是服务器端把字符写到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编码,应该都可以显示正常。
|
|