我有如下需求:
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.
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的步骤,这样是没问题的;
但是我希望省略这样的操作,请问怎么才能做到呢?
URLConnection conn = url.openConnection();
OutputStream out = conn.getOutputStream();
out.write(bufferOut);
out.flush();
out.close(); InputStream is = conn.getInputStream();
is.read(bufferIn);
}
这么改。
谢谢你的回复。
这个我知道。
但是我的需求是将
URLConnection conn = url.openConnection();
放到循环外,做到重用connection的效果。
尝试过了,依然是同样的异常。
或许我换一种问法:
如何建立一个UrlConnection的长连接,
通过这个长连接不断向同一个Server发送和接受数据?
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有比较具体的解释,包括你这个问题。
http://www.cnblogs.com/tuyile006/archive/2011/02/22/1961679.html