for(int i=0; i<3; i++)
{
URL url = new URL("http://localhost/network_test.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes("some data to send");
wr.flush();
wr.close();
// prepare request to server
// ...
// recive data from server
connection.disconnect();
}
URL url = new URL("http://localhost/network_test.php");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
for(int i=0; i<3; i++)
{
DataOutputStream wr = new DataOutputStream(
connection.getOutputStream ());
wr.writeBytes("some data to send");
wr.flush();
wr.close();
// prepare request to server
// ...
// recive data from server
}
connection.disconnect();
第一个选项工作完美!
但为什么我不能使用#2版本?每次我必须创建新对象HttpUrlConnection?为什么呢?
#2版本错误:
java.net.ProtocolException:在读取响应后无法写入请求体
答案 0 :(得分:1)
URLConnection的实例不可重用:您必须为资源的每个连接使用不同的实例
- http://developer.android.com/reference/java/net/URLConnection.html