如何以字节形式发送图像,并在同一个 HTTP 请求中一起发送 json 数据?

How to send image as bytes, and send json data together in the same HTTP request?

我正在尝试以字节形式发送图像,因为 base64 字符串占用了带宽。我看过有关将其作为流传输的示例 但问题是我不确定如何在同一个 http 请求中用它传输 json 数据

您可以在 JSON 中添加一个字段以容纳 ImageByte[]

JSON 可能是这样的:

{
    ...,

    "Image": [83, 97, 105, 102, 32, 115, 97, 121, 115, 32, 104, 101, 108, 108, 111],//Byte array of your image

    ...
}

如果您需要将带宽使用量减少到最大,只需像这样发送数据:

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 );