2012-02-21 49 views
0

首先,我打开一个连接并将一些数据发送到服务器。接下来我收到回复。在java.net.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())); 
... 

我需要的是重复整个循环 - 发送数据并接收答案。问题是,如果我使用相同的对象,则得到IOException:流关闭。如果我尝试做一个新的对象:

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

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

有什么方法可以重新打开连接?

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

回答

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. 
+0

谢谢!事实证明,这是一个简单的解决方案,显然工作(在添加'connection.setDoOutput(true);'后) – alex 2012-02-21 12:19:23