我需要一些关于如何在 Java/Android 中做某事的解释。我需要构造一个字节数组/数据包,以便我可以通过 http 请求发送它。我需要它看起来像这样:
- 3 bytes reserved (zero padded)
- 1 byte - Operation Group
- 1 byte - Packet type
- the rest depends on the above
但我不知道如何构造这样的 byte[]
。
这是我尝试过的:
String padding = "0000000000"; // first part of packet
String group = "0xA"; // second part of packet
String type = "02"; // third part of packet
String content = "ThisIsATestStringWhichYouWillReadButItsADumbAssStringDudeSorryForYou"; // last part of packet
String wholePacket = padding.concat(group.concat(type.concat(content)));
Log.v("","wholePacket : "+wholePacket);
byte[] bytes = EncodingUtils.getBytes(wholePacket, "UTF-8");
有什么建议吗?
最佳答案
您只需创建一个大小为 sizeof(rest)
+ 3 + 1 + 1 的 byte[]
:
byte[] payload = new byte[] { 0xCA, 0xFE }; // use whatever you need to get your payload into bytes
byte[] buf = new byte[3 + 1 + 1 + payload.length];
// new arrays are automatically initialized with 0, so you don't need to set bytes 0-2 to 0x00
buf[3] = 0x0A; // group
buf[4] = 4; // type
// copy payload into the target
System.arraycopy(payload, 0, buf, 3 + 1 + 1, payload.length);
但是,我建议您使用 Stream 而不是 byte[],因为无论如何您都需要通过 HTTP 连接(已经是流)发送它:
byte[] payload = new byte[] { 0xCA, 0xFE };
OutputStream target = ... // get the output stream of you http connection.
byte group = 0x0a;
byte type = 4;
target.write(new byte[] { 0x00, 0x00, 0x00, group, type }, 0, 5);
target.write(payload);
target.flush();
关于java - Android如何构造与此类似的字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848011/