8

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!
3
  • Is there any reason why you convert the bytes to strings instead of writing them raw into the output stream? Commented Jul 18, 2012 at 14:07
  • Because the write() method of OutputStreamWriter accepts char[] or string. Not byte[]. Commented Jul 18, 2012 at 14:14
  • 1
    Try using a DataOutputStream instead. Commented Jul 18, 2012 at 14:27

1 Answer 1

17

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

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

3 Comments

'conn' is an HttpURLConnection. getOutputStream() does not return a 'DataOutputStream', nor can it be casted.
Ugh sorry. Need coffee. DataOutputStream dataStream = new DataOutputStream(conn.getOutputStream());
Be cautious with this. Although it will allow you to write a byte[] to the output, the other methods of DataOutputStream are not compatible with OutputStremWriter. In particular, OutputStreamWriter can be given a standard encoding for writing Strings, where DataOutputStream has it's own proprietary encodings.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.