【问题标题】:How to send image as bytes, and send json data together in the same HTTP request?如何将图像作为字节发送,并在同一个 HTTP 请求中一起发送 json 数据?
【发布时间】:2018-01-09 12:01:41
【问题描述】:

我正在尝试将图像作为字节发送,因为带宽正在被 base64 字符串杀死。我已经看到有关将其作为流传输的示例 https://stackoverflow.com/a/17573179/8359785 但问题是我不确定如何在同一个 http 请求中传输 json 数据

【问题讨论】:

  • JSON 中添加一个字段以容纳图像 Bytes
  • 当 json 无法处理二进制数据时怎么办,_,或者我在这里遗漏了什么?
  • JSON中添加您的图片Byte[]
  • 使用多部分?一部分用于 Json,一部分用于图像。我会尝试提供一些有用的信息/示例代码,但我不知道您使用的是什么库等。

标签: java image http base64 transfer


【解决方案1】:

如果您需要最大程度地减少带宽使用,只需发送这样的数据:

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

【讨论】:

  • 服务器如何接收这两个东西? O.o
  • @BluEOS OP 要求提供 HTTP 帖子,但您给出了 Socket 的答案?
【解决方案2】:

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

JSON 可能是这样的:

{
    ...,

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

    ...
}

【讨论】:

  • 这确实奏效了,没想到会奏效。非常感谢!不过,我也会尝试其他解决方案,看看哪种方案能尽可能多地节省带宽。
  • 经过测试差异,这似乎使用的带宽量是传输 base64 时的两倍。但是,很高兴知道字节可以包含在 json 中
  • 我给出了如何在 JSON 中容纳字节的答案,如果你想节省带宽,最好这样做。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
  • 2019-12-11
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
相关资源
最近更新 更多