【问题标题】:HttpUrlConnection must be declared every time?每次都必须声明HttpUrlConnection?
【发布时间】:2016-04-01 16:49:46
【问题描述】:

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: 读取响应后无法写入请求正文

【问题讨论】:

    标签: java android http network-programming


    【解决方案1】:

    URLConnection 的实例不可重用:您必须为每个资源连接使用不同的实例

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

    【讨论】:

    • 所以,我创建了新的 HttpUrlConnection 我发送和我创建...我发送...。一遍又一遍......谢谢:)
    • 您可以重复使用该 URL。
    • 我知道的网址。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 2014-01-01
    • 2021-03-28
    • 1970-01-01
    相关资源
    最近更新 更多