我有如下需求:
1.
URL url = new URL("");
URLConnection conn = url.openConnection();
conn.setRequestProperty("content-type", "text/html");  
conn.setDoOutput(true);2.利用循环不断往此conn中写入并读取
while(true){
  
  OutputStream out = conn.getOutputStream();
  out.write(bufferOut);
  out.flush();
  out.close();  InputStream is = conn.getInputStream();
  is.read(bufferIn);
}运行后抛出异常
Exception in thread "main" java.net.ProtocolException: Cannot write output after reading input.若我在循环内部每次都执行1的步骤,这样是没问题的;
但是我希望省略这样的操作,请问怎么才能做到呢?

解决方案 »

  1.   

    while(true){
      URLConnection conn = url.openConnection();
      OutputStream out = conn.getOutputStream();
      out.write(bufferOut);
      out.flush();
      out.close();  InputStream is = conn.getInputStream();
      is.read(bufferIn);
    }
    这么改。
      

  2.   


    谢谢你的回复。
    这个我知道。
    但是我的需求是将
    URLConnection conn = url.openConnection();
    放到循环外,做到重用connection的效果。
      

  3.   

    那你去掉循环里面那句: out.close()试试
      

  4.   

    可以试一试,但是要注意到HTTP协议的特点哦你要发收据,发一次,连一次,这是不能改变的。
      

  5.   

    谢谢3楼和4楼的回复。
    尝试过了,依然是同样的异常。
    或许我换一种问法:
    如何建立一个UrlConnection的长连接,
    通过这个长连接不断向同一个Server发送和接受数据?
      

  6.   

    应该是不可以
    url.openConnection()返回的运行类是HttpURLConnection
    (Jdk1.6返回的是sun.net.www.protocol.http.HttpURLConnection而不是java.net.HttpURLConnection,不过这跟这个问题关系不大)HttpURLConnection的文档有说到:Each HttpURLConnection instance is used to make a single request but the underlying network connection to the HTTP server may be transparently shared by other instances. Calling the close() methods on the InputStream or OutputStream of an HttpURLConnection after a request may free network resources associated with this instance but has no effect on any shared persistent connection.注意红字部分,即每个HttpURLConnection实例只能用来做单独一次请求
    虽然后台有对连接的调度和分享策略,但用户代码中定义的HttpURLConnection实例不能反复发送请求,这就是为什么报出那个异常的原因了。楼主还可以看看这篇http://www.blogjava.net/xinwuhen/archive/2008/03/01/183159.html
    对UrlConnection有比较具体的解释,包括你这个问题。
      

  7.   

    是的,除了http1.1默認是持久連接,可以想像,openConnection的實現中包含了底層tcp的連接過程,所以重複使用URLConnection對象的話或缺少這一對http通信來說必要的步驟,因此會拋出異常具體看:
    http://www.cnblogs.com/tuyile006/archive/2011/02/22/1961679.html