java - 每次都必须声明 HttpUrlConnection 吗?

标签 java android http network-programming

1

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();
    }

2

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: cannot write request body after response has been read

最佳答案

Instances of URLConnection are not reusable: you must use a different instance for each connection to a resource

-- http://developer.android.com/reference/java/net/URLConnection.html

关于java - 每次都必须声明 HttpUrlConnection 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36361719/

相关文章:

java - 每行包含多个字符串的 ListFragment

http - Google Cloud Storage 文件缓存和过期问题

python - 如何使用redis for python在Redis中搜索值

angularjs - 如何使用 http get 为 angular.service 编写 Jasmine 测试?

java - eclipse 无法将 Maven 项目识别为 java

java - 为什么 EvaluatorFilter 不过滤不匹配的语句?

安卓 6 : cannot share files anymore?

Java图像缩放而不将整个图像加载到内存中

java - 需要从java调用c库

Android 在应用程序启动时启动系统服务