在java.net.HttpURLConnection中重新打开连接的方法

时间:2012-02-21 00:14:34

标签: android httpurlconnection

首先,我打开一个连接并将一些数据发送到服务器。接下来我得到回复。

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:stream closed 。如果我尝试制作一个新对象:

wr = new OutputStreamWriter(connection.getOutputStream());

我得到 ProtocolException:OutputStream不可用,因为请求标头已经发送了!。如果我断开连接并建立新连接并不重要 - 它都是一样的。

有没有办法重新开启连接?

我在Android上制作它,但我不确定它是否会对这种情况产生任何影响。

1 个答案:

答案 0 :(得分:1)

您需要再次致电url.openConnection()并获得新连接。如果请求是针对同一主机,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.
相关问题