3

I would like to open an URL and submit the following parameters to it, but it only seems to work if I add the BufferedReader to my code. Why is that?

Send.php is a script what will add an username with a time to my database.

This following code does not work (it does not submit 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 does work:

        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();
Raedwald
  • 46,613
  • 43
  • 151
  • 237
Kevin S
  • 172
  • 2
  • 11
  • 1
    Consider using some third-part library if you need to work with HTTP. `Apache HttpClient` is pretty good. It's not very comfort to work with network with build-in Java facilities – coolguy Jan 04 '16 at 18:02

1 Answers1

7

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

You need to at least call the getInputStream() or getResponseCode() for the connection to be committed so that the server that the url is pointing to able to process the request.

kucing_terbang
  • 4,991
  • 2
  • 22
  • 28
  • 3
    Looking at the JDK source code confirms. The connection doesn't send the request until you call `getInputStream()` – Monz Jan 04 '16 at 20:29