0

I have the following code for connecting to a url. My problem, is that when I run it in debug, I see that connected = false and none of the other parameters that I am trying to set are working (such as timeout). Can anyone help me with this? What am I doing wrong??

And before anyone asks, my manifest has the internet permission.

private static class SyncOperation extends AsyncTask<String, String, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
        HttpsURLConnection urlConnection = null;
        URL url = null;
        String msg = "Good";
        int code = 0;
        try {
            System.setProperty("http.keepAlive", "false");
            url = new URL("https://www.google.com");
            urlConnection =  (HttpsURLConnection) url.openConnection();
            urlConnection.setInstanceFollowRedirects(false);
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(15000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
        } catch (MalformedURLException e) {
            msg = "Bad MalformedURLException";
            e.printStackTrace();
            Log.e("HTTPS", e.getMessage());
        } catch (IOException e) {
            msg = "Bad IOException";
            e.printStackTrace();
            Log.e("HTTPS", e.getMessage());
        } finally {
            urlConnection.disconnect();
            Log.d("HTTPS", msg);
            Log.d("HTTPS", "diconnected");
        }

        return code;
    }

    @Override
    protected void onPostExecute(Integer code) {
        super.onPostExecute(code);

        Toast t = Toast.makeText(mContext, code.toString(), Toast.LENGTH_SHORT);
        t.show();

    }

}
Meir
  • 1,943
  • 5
  • 22
  • 38

1 Answers1

2

You are only configuring your connection, but you don't connect it. The name of the method url.openConnection() is misleading: it does not open a connection. it only gives you a connection object, which is not connected initially.

You need to invoke any of the methods which cause the connection to connect, e.g. connect().

In other words, try to actually do something with your connection, like reading the content and writing it to System.out.println(). That will open the connection automatically.

Daniel S.
  • 6,458
  • 4
  • 35
  • 78