我试图理解字节 [] 到字符串,字节 [] 到字节 [] 转换的字符串表示…我将我的字节 [] 转换为要发送的字符串,然后我期望我的 Web 服务(用 python 编写)将数据直接回显给客户端。
当我从我的 Java 应用程序发送数据时…
Arrays.toString(data.toByteArray())
要发送的字节..
[B@405217f8
发送(这是 Arrays.toString() 的结果,它应该是我的字节数据的字符串表示,该数据将通过网络发送):
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
在python端,python服务器返回一个字符串给调用者(我可以看到和我发送给服务器的字符串一样
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
服务器应将此数据返回给客户端,以便在客户端进行验证。
我的客户收到的响应(作为字符串)看起来像
[-47, 1, 16, 84, 2, 101, 110, 83, 111, 109, 101, 32, 78, 70, 67, 32, 68, 97, 116, 97]
我似乎无法弄清楚如何将接收到的字符串恢复为 byte[]
无论我尝试什么,我最终都会得到一个字节数组,如下所示……
[91, 45, 52, 55, 44, 32, 49, 44, 32, 49, 54, 44, 32, 56, 52, 44, 32, 50, 44, 32, 49, 48, 49, 44, 32, 49, 49, 48, 44, 32, 56, 51, 44, 32, 49, 49, 49, 44, 32, 49, 48, 57, 44, 32, 49, 48, 49, 44, 32, 51, 50, 44, 32, 55, 56, 44, 32, 55, 48, 44, 32, 54, 55, 44, 32, 51, 50, 44, 32, 54, 56, 44, 32, 57, 55, 44, 32, 49, 49, 54, 44, 32, 57, 55, 93]
或者我可以获得如下字节表示形式:
B@2a80d889
这两个都与我发送的数据不同……我确定我错过了一些非常简单的东西……
有什么帮助吗?!
原文由 0909EM 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不能只获取返回的字符串并从中构造一个字符串……它不再是
byte[]
数据类型,它已经是一个字符串;你需要解析它。例如 :** 编辑**
You get an hint of your problem in your question, where you say ”
Whatever I seem to try I end up getting a byte array which looks as follows... [91, 45, ...
“, because91
is the byte value for[
, so[91, 45, ...
是字符串“[-45, 1, 16, ...
”字符串的字节数组。方法
Arrays.toString()
将返回指定数组的String
表示;这意味着返回值将不再是数组。例如 :As you can see,
s1
holds the string representation of the arrayb1
, whiles2
holds the string representation of the bytes contained inb1
。现在,在您的问题中,您的服务器返回类似于
s1
的字符串,因此要取回数组表示形式,您需要相反的构造函数方法。如果s2.getBytes()
是new String(b1)
的对立面,你需要找到Arrays.toString(b1)
的对立面,因此我粘贴了这个答案的第一个代码片段。