Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Write byte array to OutputStreamWriter

I have an application that uploads photos through a web service. In the past, I loaded a file into a stream, and converted to Base64. Then I posted the resulting string through the write() method of an OutputStreamWriter. Now, the web service has changed, and it expects multipart/form-data and it does not expect Base64.

So somehow I need to post the chararters of this file as is without conversion. I'm sure I'm close, but all I ever get is a content lengh underflow or overflow. The odd thing is that in the debugger I can see that my buffer length is the same length as the string I'm posting. Here's what I'm doing and hopefully enough code:

// conn is my connection
OutputStreamWriter dataStream = new OutputStreamWriter(conn.getOutputStream());

// c is my file
int bytesRead = 0;
long bytesAvailable = c.length();

while (bytesAvailable > 0) {
   byte[] buffer = new byte[Math.min(12288, (int)bytesAvailable)];
   bytesRead = fileInputStream.read(buffer, 0, Math.min(12288, (int)bytesAvailable));

   // assign the string if needed.
   if (bytesRead > 0) {
      bytesAvailable = fileInputStream.available();

      // I've tried many encoding types here.
      String sTmp = new String(buffer, "ISO-8859-1");
      // HERE'S the issue.  I can't just write the buffer,
      dataStream.write(sTmp);
      dataStream.flush();
// Yes there's more code, but this should be enough to show why I don't know what I'm doing!
like image 226
Paul Avatar asked Jul 18 '12 14:07

Paul


1 Answers

change

OutputStreamWriter dataStream = new OutputStreamWriter(conn.getOutputStream());

with this

DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream()); 

and directly call dataStream.write(buffer);

let me know how it behave

Edit: edited answer according to comment

like image 111
AAnkit Avatar answered Sep 22 '22 09:09

AAnkit