在url对象中使用流

时间:2012-01-31 00:58:02

标签: inputstream outputstream urlconnection

我正在使用客户端 - 服务器方案。客户端使用url连接与服务器(servlet)通信。这是我正在使用的代码。

 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. 

我哪里错了?

1 个答案:

答案 0 :(得分: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();