当前位置: 代码迷 >> Java Web开发 >> 一个byte[] 数组传递的有关问题,
  详细解决方案

一个byte[] 数组传递的有关问题,

热度:95   发布时间:2016-04-16 22:04:44.0
请教高手一个byte[] 数组传递的问题,高手请进,在线等
我使用 HttpURLConnection 传递byte数组时,在接收方获得的数据不对
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
 out = conn.getOutputStream();
out.write(我拼的字节数组)

字节数组的内容大致为:
 byte[] a = new byte[]{98,95,-127,15,52,3,0,9};
          byte[] b = "a=".getBytes();
然后将a和b合并为一个大的数组c
out.write(c)



我在action中通过
request.getParameter("a").getBytes();  发现传递过来的 负数的byte全部变为正数了
传送的byte[]为:

接到的byte[]为:



本人QQ:3011563421
------解决方案--------------------
但是有时候你无法修改字符编码,或者修改字符编码是不太好的做法,比如你的情况,HTTP环境下,优先用文本格式发送数据,除非你在发送超大文件,比如图片,否则不应该发送乱七八糟的字节数据,如果真的要发送,请先用BASE64编码成字符串,再发送。
所以5楼的代码可以写成:
	public static void main(String[] args) throws Exception {
byte[] bys1 = {98, 95, -127, 15, 32, 3, 0, 9};
System.out.println(Arrays.toString(bys1));

BASE64Encoder encoder = new BASE64Encoder();
String str = encoder.encode(bys1);

BASE64Decoder decoder = new BASE64Decoder();
byte[] bys2 = decoder.decodeBuffer(str);

System.out.println(Arrays.toString(bys2));
}


具体到你这个需求
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
out = conn.getOutputStream();
byte[] a = new byte[]{98,95,-127,15,52,3,0,9};
BASE64Encoder encoder = new BASE64Encoder();
String str = "a=" + encoder.encode(a);
byte[] b = str.getBytes();
out.write(b);


String str = request.getParameter("a");
BASE64Decoder decoder = new BASE64Decoder();
byte[] a = decoder.decodeBuffer(str);
  相关解决方案