记:Nett发送HEX值,转码后中文乱码问题

在项目中遇到服务端通过Netty发送HEX值,转换后出现中文乱码的问题。尝试通过设置`HexString2Buf`方法中`src.getBytes("UTF-8")`来解决,但未见效。最终发现是字符串转HEX过程缺少编码定义,修改相关方法后,调试成功解决了乱码问题。

项目场景:

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();
	}

调试代码,果然成功了
操作成功

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值