0

I have a problem with java.lang.Object stream. InputStream actually is a real Object[]. readObject method reads only one object. How can I read stream objects correctly? Sample code is below.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    InputStream stream = request.getInputStream();
    byte[] streamBytes = stream.readAllBytes();
    ByteArrayInputStream bis = new ByteArrayInputStream(streamBytes);
    ObjectInput in = null;
    try {
        in = new ObjectInputStream(bis);
        Object o = in.readObject();

        System.out.println(o.getClass()); // Prints: class [Ljava.lang.Object;
        System.out.println(o.getClass().getSimpleName()); // Prints: Object[]

    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}
5
  • 1
    An array is also a type of object. So your code read an object, and that object is an array, containing other objects. Cast it to Object[] and you're good to go. That said, in general I would recommend you avoid using Java serialization, and instead use XML or JSON style serialization, as that is more portable. Commented Mar 27, 2022 at 12:13
  • @MarkRotteveel You are saying as Object[] objects = (Object[]) o I am new to Java. Can you help me about syntax? Commented Mar 27, 2022 at 13:18
  • You are right. XML or JSON would be a good choice. this object contains binary data. I didn't develop this API. I am sending http request to external API endpoint. Commented Mar 27, 2022 at 13:26
  • ObjectInputStream is outdated and can be insecure (code injection into Java app9 if you don't use setObjectInputFilter (requires Java 9) on it and configure the stream correctly. Commented Mar 28, 2022 at 9:16
  • You don't need half of this code. ois - new ObjectInputStream(request.getInputStream()) and a loop calling ois.readObject() will do, terminating when EOFException is caught. You don't need readAllBytes() or the ByteArrayInputStream(): both are just a waste of time and space. Commented Mar 29, 2022 at 23:04

0

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.