簡體   English   中英

如何以字節為單位發送圖像,並在同一HTTP請求中一起發送json數據?

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

我正在嘗試以字節為單位發送圖像,因為帶寬被base64字符串殺死了。 我已經看到了有關將其作為流傳輸的示例https://stackoverflow.com/a/17573179/8359785,但問題是我不確定如何在同一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 ); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM