2010-06-02 29 views
1

我需要通过序列化从客户端发送一个对象到服务器。
这是我的代码:StreamCorruptedException,当使用ObjectInputStream

 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中,我可以通过那里检索对象。
唯一的问题是,一旦我达到这一行:

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

我得到一个异常StreamCorruptedException,在客户端。 (在服务器端一切工作太棒了!) 如果我走这条线断,该servlet未触发(我指的是doGet()doPost()不会被调用在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) 

感谢,

+0

什么是确切的错误? – 2010-06-02 14:07:10

+0

编辑问题 – rayman 2010-06-02 14:09:08

回答

4

客户期待这个servlet把对象回反应是这样的:

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

但该servlet显然其实没有写任何对象返回。所以客户不应该用ObjectInputStream来装饰它。只是这样做:

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

或者干脆

connection.connect(); 

,如果你不感兴趣的响应反正。连接仅按需执行。 getInputStream()将隐含地做到这一点。这就是为什么在您致电getInputStream()之前请求未被解雇。另请参阅this answer了解更多提示。

+0

connection.connect(); ,没有触发对方 而是InputStream inputStream; // ... inputStream = connection.getInputStream(); 完美地完成了这项工作。 谢谢。 – rayman 2010-06-02 15:21:47

+0

@BalusC在这里我需要用输入流代替oos啊?我面临着同样的错误,我的代码是ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(baos); os。的writeObject(串行化); os.reset(); os.close(); – AndroidOptimist 2014-03-13 10:00:56

0

不要自己做这个东西,看的HttpClient和春天的HttpInvoker。

+0

这是一个严肃的答案,我开始写一个客户端/服务器应用程序,就像上面那样。当我发现HttpInvoker时,我意识到了我的愚蠢;我永远不会回去。 – Justin 2010-06-02 14:25:09

+0

在BalusC的链接答案中查看** Last Words **。 – Justin 2010-06-02 14:27:04

+0

因为你的意图很好,所以我抵消了downvote。但你今后应该多发一点扩展答案。只需*实际回答问题,然后关闭使用Apache HttpClient的建议,如有必要,随代码示例如何使用HttpClient进行操作。现在你不回答核心问题,甚至不知道如何使用HttpClient。 – BalusC 2010-06-02 14:33:43

相关问题