user6145907
user6145907

Reputation: 11

HttpUrlConnection must be declared every time?

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

First options work perfect!

But why i can't use #2 version? Every time I must create new object HttpUrlConnection? Why?

Error at #2 version:

java.net.ProtocolException: cannot write request body after response has been read

Upvotes: 1

Views: 415

Answers (1)

F43nd1r
F43nd1r

Reputation: 7749

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

Upvotes: 1

Related Questions