2012-01-31 30 views
0

我正在使用客戶端 - 服務器方案。客戶端使用url連接與服務器(這是一個servlet)進行通信。這裏是我使用的代碼。在url對象中使用流

URL url = new URL("http://localhost:8080/hello"); 
    URLConnection connection = url.openConnection(); 
    connection.setDoOutput(true); 
    ObjectOutputStream out=new ObjectOutputStream(connection.getOutputStream());//1st out put stream 
    out.writeObject(pk); 
    out.flush(); 
    out.close(); 

    ObjectInputStream in = new ObjectInputStream(connection.getInputStream());//1st instream 
    PublicKey spk=(PublicKey)in.readObject(); 
    in.close(); 

    ObjectOutputStream out1=new ObjectOutputStream(connection.getOutputStream());//2nd out put stream 
    out1.writeObject(str1); 
    out1.flush(); 
    out1.close(); 

    ObjectInputStream in1 = new ObjectInputStream(connection.getInputStream());  
    String rstr3=(String)in1.readObject(); 
    //processing 
    in1.close(); 

但我正在逐漸稱爲異常:

java.net.ProtocolException:Cannot write output after reading input. 

我要去哪裏錯了?

回答

0

URLConnection的實例不可重用:您必須爲資源的每個連接使用不同的實例。以下代碼正常工作(打開一個新的urlconnection對象)

URLConnection connection1 = url.openConnection(); 
ObjectOutputStream out1=new ObjectOutputStream(connection1.getOutputStream());//2nd out put stream 
    out1.writeObject(str1); 
    out1.flush(); 
    out1.close(); 

    ObjectInputStream in1 = new ObjectInputStream(connection1.getInputStream());  
    String rstr3=(String)in1.readObject(); 
    //processing 
    in1.close(); 
+0

什麼是更清潔,更實用的替代方案?有沒有簡單的東西可以縮短,而不是每一次都這麼做? – Trup 2012-08-19 02:13:38

+0

@滴:我沒有嘗試過,但我認爲你可以在調用conection.disconnect()後再次使用連接對象。如果可能的話,試試讓我知道。 – Ashwin 2012-08-19 06:38:43