Why HttpURLConnection does not send an HTTP request

I would like to open the URL and send the following parameters to it, but it only works if I add BufferedReader to my code. Why is this?

Send.php is a script that will add the username over time to my database.

This following code does not work (it does not transfer any data to my database):

        final String base = "http://awebsite.com//send.php?";
        final String params = String.format("username=%s&time=%s", username, time);
        final URL url = new URL(base + params);

        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Agent");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

But this code really works:

        final String base = "http://awebsite.com//send.php?";
        final String params = String.format("username=%s&time=%s", username, time);
        final URL url = new URL(base + params);

        final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent", "Agent");
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.connect();

        final BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
        }

        connection.disconnect();
+1
source share
1 answer

As far as I know. When you call a function connect(), it will create a connection only.

getInputStream() getResponseCode() , , , url, .

+2

Source: https://habr.com/ru/post/1666004/


All Articles