3

I'm using HttpClient to post then retrieve something in Android, which works great, but when I dont have a internet connection it forces close, is their a way to catch UnknownHostException when making an HttpPost? I know I could make sure its connected to the internet before making the request, but what about if the phone just doesn't have service?

William L.
  • 3,846
  • 9
  • 53
  • 72
  • Checkout this answer about Android's `ConnectivityManager`: http://stackoverflow.com/a/4009133/180740 – Philipp Reichart Jun 26 '12 at 15:42
  • possible duplicate of [How to check internet access on Android? InetAddress never timeouts](http://stackoverflow.com/questions/1560788/how-to-check-internet-access-on-android-inetaddress-never-timeouts) – Philipp Reichart Jun 26 '12 at 15:43

2 Answers2

7

UnknownHostException is a Subclass of IOException, so you should be able to catch/manage it simply catching IOException or something more specific (NoRoute, ConnectTimeout, etc.)

Also consider adding connection check before doing network calls with ConnectivityManager

Shine
  • 3,788
  • 1
  • 36
  • 59
3

you can check for your intenet connection with

            ConnectivityManager cm = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected() || cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
                    //connected
            } else {
                    //not connected
            }

And set the permissions in AndroidManifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Mario Naether
  • 1,122
  • 11
  • 22