开发者

How to upload binary data using POST

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 B开发者_如何学JAVAase64 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)


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜