1

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)

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I already tried using MultipartEntity but thanks to you, I tried it once again and now it worked! :)
0

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

1 Comment

I tried concatenating the string gotten this way to my StringBuilder but, unfortunately, it doesn't work :( I am getting the same result as before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.