StreamCorruptedException, when using ObjectInputStream

扶醉桌前 提交于 2021-02-11 08:51:04

问题


I need to send an Object from client to server by serializing it.
This is my code:

     HttpURLConnection con = null;
     ObjectOutputStream out = null;
     ObjectInputStream inputStream = null;

     URL servlet = new URL("MY_URL");
        con = (HttpURLConnection) servlet.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        con.setDefaultUseCaches(false);
        con.setRequestProperty("Content-type", "application/octet-stream");
        con.setRequestMethod("POST");
        out = new ObjectOutputStream(con.getOutputStream());
        out.writeObject(myobject);
        out.flush();
        out.close();

        inputStream = new ObjectInputStream(con.getInputStream());
        inputStream.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    finally
    {
    //  inputStream.close();
        con.disconnect();
    }
    return true;

Now, I am able to reach the Servlet, and I can retrieve the object through there.
The only problem is that as soon as I reach to this line:

inputStream = new ObjectInputStream(con.getInputStream());

I get an exception StreamCorruptedException, at the client side. (at the server side everything working great!) And if I take this line off, the servlet not being triggered (I mean the doGet() or doPost() not being called in the servlet)

What am I doing wrong?

This is the exact error:

06-02 12:41:53.549: WARN/System.err(4260): java.io.StreamCorruptedException
06-02 12:41:53.549: WARN/System.err(4260): java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:2399)
06-02 12:41:53.549: WARN/System.err(4260): at java.io.ObjectInputStream.<init>(ObjectInputStream.java:447) 

Thanks,
Ray


回答1:


The client is expecting that the servlet writes an object back to the response something like:

ObjectOutputStream oos = new ObjectOutputStream(response.getOutputStream());
oos.writeObject(someObject);

But the servlet apparently actually doesn't write any object back. So the client should not decorate it with an ObjectInputStream. Just do so:

InputStream inputStream;
// ...
inputStream = connection.getInputStream();

or simply

connection.connect();

if you're not interested in the response anyway. The connection is executed on demand only. The getInputStream() will do that implicitly. That's why the request is not been fired until you call getInputStream(). Also see this answer for more hints.




回答2:


Don't do this stuff yourself, look at HttpClient and spring's HttpInvoker.



来源:https://stackoverflow.com/questions/2958385/streamcorruptedexception-when-using-objectinputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!