3

Can anyone tell me if there is a way to read/output the contents of a DataOutputStream? I am obtaining one using

new DataOutputStream( httpUrlConnection.getOutputStream() );

and am writing some post data to it. I would like to be able to see what data i am posting after writing to this output stream but cannot find a simple way.

Thanks for any help!

Dori
  • 18,283
  • 17
  • 74
  • 116

1 Answers1

2

Sure you can 'see' the 'contents' of a DataOutputStream - I imagine it wouldn't be what you expected though! I imagine what you want to be able to do is examine the data getting passed through the stream, quite impossible with the regular class - indeed the very definition of a stream is that it doesn't contain all the data being managed by it, at any one time.

If you really need to be able to audit the data that you've supplied to any output stream then you could do something like this:

import java.io.DataOutputStream;

public class WatcherOutputStream extends DataOutputStream {
     private byte[] data = null;

     public WatcherOutputStream(OutputStream delegateStream) {
        super(delegateStream);
     }

     public void write(byte[] b) {
        // Store the bytes internally

        // Pass off to delegate
        super.write(b);
    }
 }

The data saving code and remaining write methods are left to you as an exercise. Of course, this is a horrible way to track the data you are writing out to the stream - it's an extra layer of overhead in both memory and speed. Another options would be to use AOP to examine the data as you write it. This method has the advantages of being less intrusive to your code, and easily maintainable in that you can easily add and remove point cuts without modifying your main program. I suspect that AOP may be more complicated a solution than you are looking for right now, but I am including this link to more reading, just in case it will be helpful.

Community
  • 1
  • 1
Perception
  • 79,279
  • 19
  • 185
  • 195
  • 1
    Cool, thanks. I did write a class similar to this to get the debug data around the same time you posted this. Am now looking into using 'Charles' web debug proxy app for a similar purpose! – Dori Jun 24 '11 at 11:22
  • +1 on the Charles proxy tool. It looks pretty promising for any kind of web development! – Perception Jun 24 '11 at 13:18