项目场景:
JAVA 使用NETTY框架建立socket数据通讯问题描述:
服务端将定义好的字符串,转HEX值,回复到客户端,客户端将字符串转码解析后中文乱码String strTo16 = HexUtils.strTo16(json.toString());
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
服务端回复
ByteBuf resp = Unpooled.copiedBuffer(HexUtils.HexString2Buf(strTo16 ));
ChannelFuture writeAndFlush = ctx.writeAndFlush(resp);
HexString2Buf 方法
public static byte[] HexString2Buf(String src) {
int len = src.length();
byte[] ret = new byte[len / 2];
byte[] tmp;
try {
tmp = src.getBytes("UTF-8");
for (int i = 0; i < len; i += 2) {
ret[i / 2] = uniteBytes(tmp[i], tmp[i + 1]);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return ret;
}
public static byte uniteBytes(byte src0, byte src1) {
try {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }, "UTF-8")).byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1;
_b1 = Byte.decode("0x" + new String(new byte[] { src1 }, "UTF-8")).byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
} catch (Exception e) {
return 0;
}
}
原因分析:
一直以为HexString2Buf 转 byte[]时 编码原因,所以tmp = src.getBytes(“UTF-8”);设置为UTF-8编码,但是不起作用,结果还是乱码
解决方案:
后来觉的是不是字符串转HEX值时没有定义编码的原因,所以将String转HEX方法修改为:
strTo16 = HexUtils.bytesToHexString(json.toString().getBytes("UTF-8"));
public static String bytesToHexString(byte... src) {
StringBuilder stringBuilder = new StringBuilder();
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
调试代码,果然成功了