在重新开放连接java.net.HttpURLConnection中的方法 [英] Way of reopening connection in java.net.HttpURLConnection
问题描述
首先,我打开连接并一些数据发送到服务器。接下来,我得到回应。
First, I open a connection and send some data to server. Next I get a response.
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
wr = new OutputStreamWriter(connection.getOutputStream());
wr.write("some text sent to server");
wr.flush();
//read the server answer
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
...
我需要的是再次重复整个循环 - 发送数据和接收答案。现在的问题是,如果我使用相同的 WR 的对象,我得到的 IOException异常:流闭的。如果我尝试做一个新的对象:
What I need is to repeat the whole cycle again - send data and receive answer. The problem is that if I use the same wr object I get the IOException: stream closed. And if I try to make a new object:
wr = new OutputStreamWriter(connection.getOutputStream());
我得到的的ProtocolException:因为请求头已经发送的OutputStream不可用的!如果我断开并建立新的连接不要紧 - 这都是一样的。
I get ProtocolException: OutputStream unavailable because request headers have already been sent!. It doesn't matter if I disconnect and make a new connection - it is all the same.
有什么办法重新连接?
和我让它在Android,但我真的不知道,如果它使在这种情况下任何区别。
And I make it on Android, but I'm not really sure if it makes any difference in this situation.
推荐答案
您需要再次调用 url.openConnection()
,并得到一个新的连接。如果请求是在同一主机 HttpURLConnection类
应该足够聪明重用现有的连接。从文档报价:
You need to call url.openConnection()
again and get a new connection. HttpURLConnection
should be smart enough to reuse the existing connection if the request is to the same host. Quote from the docs:
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.
这篇关于在重新开放连接java.net.HttpURLConnection中的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!