How to upload binary data using POST

2019-05-30 00:39发布

问题:

I have something like this in my code:

String boundary = "thisIsMyBoundaryString";
StringBuilder body = new StringBuilder();  
...  
byte[] data = bos.toByteArray();  
body.append(new String(data));  
body.append("\r\n--" + boundary + "--\r\n");  
String entity = body.toString();  

I'm building a POST request and need to insert some binary data (JPEG compressed bitmap).

After appending byteArray, I want to append newLine and boundary string,
but the StringBuilder gets corrupted - seems that the bytes from the added boundary
become misaligned from that point on
and they are no longer being interpreted as my original string but as some random characters.

Is this what is happening here?

How can I resolve this? Maybe I should add a byte of padding to byteArray before appending boundary?

What is the proper way of adding binary data to POST request?
Please note that using Base64 encoding is not an option here.

 
 
[edit]
Solution was to use MultipartEntity to make such requests
and forget about adding boundaries manually.

Here is relevant code snippet:

FileBody bin = new FileBody(new File(Environment.getExternalStorageDirectory() + "/" + FILE_NAME));
MultipartEntity entity = new MultipartEntity();
entity.addPart("message", new StringBody("A message that goes with request"));
entity.addPart("file", bin);

(Third line has to be inside of a try/catch block but I removed it for readability)

回答1:

I think you should use something like Apache HttpClient (or maybe it's in their http-mime module, I haven't used it myself) that can do multipart posts. See this question, for example. Binary data like a JPEG is not character data and really shouldn't be put in a String.



回答2:

I haven't tried this, but maybe this will work

byte[] data = bos.toByArray();
byte[] boundary = "\r\n--BOUNDARY--\r\n".getBytes();
byte[] fullData = new byte[data.length + boundary.length];
System.arraycopy(data, 0, fullData, 0, data.length);
System.arraycopy(boundary, 0, fullData, data.length, boundary.length);
String entity = new String(fullData);