你不能只使用返回的字符串并从中构造一个字符串……它不再是
byte[]数据类型,它已经是一个字符串;你需要解析它。例如 :
String response = "[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]"; // response from the Python scriptString[] bytevalues = response.substring(1, response.length() - 1).split(",");byte[] bytes = new byte[bytevalues.length];for (int i=0, len=bytes.length; i<len; i++) { bytes[i] = Byte.parseByte(bytevalues[i].trim()); }String str = new String(bytes);编辑
你会在问题中得到提示,你说“
Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...”,因为91是的字节值[,所以
[91, 45, ...字符串
“ [-45, 1, 16, ...”的字节数组也是如此。
该方法
Arrays.toString()将返回
String指定数组的表示形式。表示返回的值将不再是数组。例如 :
byte[] b1 = new byte[] {97, 98, 99};String s1 = Arrays.toString(b1);String s2 = new String(b1);System.out.println(s1); // -> "[97, 98, 99]"System.out.println(s2); // -> "abc";正如你所看到的,
s1持有的字符串表示数组
b1,而
s2持有的字符串表示的字节包含在b1。
现在,在你的问题中,你的服务器返回了一个类似于的字符串
s1,因此要获取数组表示形式,你需要相反的构造方法。如果
s2.getBytes()是的反义词
new String(b1),则需要找到的反义词
Arrays.toString(b1),因此我在此答案的第一段代码中粘贴的代码。



