Stack Exchange
httpConnection.getResponseCode() cause a ConnectException after a call to reconnect()
I encounter a strange problem using WifiManager:
The code is:
Code:
static class InitTask extends AsyncTask<Void, Integer, Integer> {

     ...

    @Override
    protected Integer doInBackground (Void... arg0) {
        WifiManager wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
        WifiConfiguration conf = new WifiConfiguration();

        conf.SSID = "\"" + site.getWifiSSID() + "\"";   // Please note the quotes. String should contain ssid in quotes

        // Only support WPA
        conf.preSharedKey = "\"" + site.getwifiWPAKey() + "\"";

        int wifiState = wifi.getWifiState();
        Boolean enabled = wifi.isWifiEnabled();

        if ((site.getSavedDeviceWifiState() != WifiManager.WIFI_STATE_ENABLED) &&
                (site.getSavedDeviceWifiState() != WifiManager.WIFI_STATE_ENABLING)) {
            wifi.setWifiEnabled(true);
        }

        wifi.disconnect();
        wifi.addNetwork(conf);
        wifi.enableNetwork(conf.networkId, true);
        wifi.reconnect(); 
        //Just to verify in debug  
        String verif = site.getWifiSSID();
    }

            // If I put a breakpoint here, the following code runs without any problem
    int responseCode = 0; 
    try {
        int i = 0;
        url = new URL(site.getDescriptionFileUrl());

        // Création d'une connection HTTP à une URL
        URLConnection connection = url.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection)connection;

                    // Next Call immediately throws a ConnectException
        responseCode = httpConnection.getResponseCode();

        if (responseCode == HttpURLConnection.HTTP_OK) {
                        ...
                   }
    }
    catch (MalformedURLException e) {
        Log.d("2ndGuide", "Malformed URL Exception." + e);
    } 
    catch (ConnectException e) {
        Log.d("2ndGuide", "ConnectException." + e);

    } 
    catch (IOException e) {
        Log.d("2ndGuide", "IO Exception." + e);
    }
    Log.d("2ndGuide", mActivity.getResources().getString(R.string.label_messageAlertCnfBadUrl));
    return -6;
}

So the problem is that if I let the code executes normally, getResponseCode() throws a ConnectException error:  
07-18 20:29:41.821: D/2ndGuide(1925): ConnectException.java.net.ConnectException: 192.168.0.50/192.168.0.50:80 - Network is unreachable

If I put a breakpoint just before then click immediately on Play, to just wait a little bit, the code runs normally.
I never seen such warning in the doc or anywhere nor a mechanism to wait for the network being ready after a call to reconnect().
What's the problem??
Edit 1:
I tried to call getResponseCode() multiple times like that:
            for (int strangeTest = 0; responseCode <= 0 && strangeTest < 10; strangeTest++) {
                try {
                    connection = url.openConnection();
                    httpConnection = (HttpURLConnection)connection;
                    responseCode = httpConnection.getResponseCode();

                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {

                    }
                }
                catch (ConnectException e) {
                    Log.d("2ndGuide", "ConnectException." + e);
                } 
                catch (IOException e) {
                    Log.d("2ndGuide", "IOException." + e);
                } 
            }   

No way, the only things which works is to add a simple sleep before calling getResponseCode():
            ...
            wifi.disconnect();
            wifi.addNetwork(conf);
            wifi.enableNetwork(conf.networkId, true);
            wifi.reconnect();   

             String verif = site.getWifiSSID();
        }

        int responseCode = 0; 
        try {
            int i = 0;
            url = new URL(site.getDescriptionFileUrl());
            URLConnection connection = null;
            HttpURLConnection httpConnection = null;

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {

            }

            connection = url.openConnection();
            httpConnection = (HttpURLConnection)connection;
            responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                 ...

Regards,
Alain

What happens when you use a browser to access a website from the AVD? It would be interesting to see your IOException stack trace too.

AVD's onboard browser perfectly works when I try to access the URL which causes problem in my application. It loads the page and don't display any error.

Ok, so we need to see the stack trace. (BTW, you app has the proper permissions set to access the network?)

The permissions are ok, the problem  doesn't ocuur if I put a breakpoint just before getResponseCode(). Where is the stack trace?

Not sure, but it seems the network is no yet ready when you try to establish your URLConnection.

Hi shlublu. that's obvious. the question is: Why? I didn't see anywhere tha we could be supposed to wait for something after a call to reconnect()!

I had a similar with android and my server.  It always turned out to be one of two issues for me. 
 1)  I used WAMP, but forgot to turn it on, on my server. I wrote a script that automatically turns on WAMP every time I turn on the server.
 2)  I was using wifi to connect from my device to the server.  The signal was not strong enough, so I moved closer to the server and it worked fine.
It sounds like it might be the second issues.  If when you used breakpoints there are no problems, than it could be the wifi does not respond quick enough.  Try putting the thread to sleep for one or two seconds to give the server more time to respond

I effectively inserted a Thread.sleep(500) and it seems to be better. Anyway it seems that the problem is not really about the server answer; if getResponseCode() returns 0 it's pretty much a problem of local network interface than a problem of remote answer so, even it's understandable to have to wait that everything get's place after reconnect(), I find strange to not find a mechanism to wait that the connection be plenty established. Or, reconect() returns to fast !?!
