我正在尝试以字节为单位发送图像,因为带宽被base64字符串杀死了。我看过有关将其作为流传输的示例
https://stackoverflow.com/a/17573179/8359785,但问题是我不确定如何在同一HTTP请求下使用它传输json数据
最佳答案
如果您需要最大程度地减少带宽使用,只需发送如下数据:
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
dOut.writeInt(imageBytes.length);
dOut.write(imageBytes);
dOut.writeInt(jsonBytes.length);
dOut.write(jsonBytes);
接收代码:
DataInputStream dIn = new DataInputStream(socket.getInputStream());
int imageBytesLength = dIn.readInt();
byte[] imageBytes= new byte[imageBytesLength];
dIn.readFully(imageBytes, 0, imageBytesLength);
int jsonBytesLength = dIn.readInt();
byte[] jsonBytes= new byte[jsonBytesLength ];
dIn.readFully(jsonBytesLength , 0, jsonBytesLength );