问题描述
我需要通过序列化将对象从客户端发送到服务器.
这是我的代码:
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;
现在,我能够到达Servlet,并且可以从那里检索对象.
唯一的问题是,只要我到达这一行:
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());
我在客户端收到一个异常StreamCorruptedException.(在服务器端,一切正常!)如果我取消这一行,则不会触发servlet(我的意思是 doGet()
或 doPost()
不会在servlet中被调用)
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)
我在做什么错了?
这是确切的错误:
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)
谢谢,
雷
推荐答案
客户端希望servlet将对象写回到响应中,例如:
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);
但是servlet显然实际上并没有写回任何对象.因此,客户端不应使用 ObjectInputStream
装饰它.只需这样做:
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();
或者简单地
connection.connect();
如果您仍然对响应不感兴趣.连接仅按需执行. getInputStream()
将隐式地执行该操作.这就是为什么直到您调用 getInputStream()
才会触发请求的原因.另请参见此答案有关更多提示.
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.
这篇关于使用ObjectInputStream时发生StreamCorruptedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!