javaandroidexceptionsocket-timeout-exceptionunknown-host

Getting UnknownHostException instead of SocketTimeOutExcepetion


I am new to android and Java. And I am trying to learn android app development from UDACITY. I was trying to run this code and I am expecting a SocketTimeOutExcepetion but what I am getting is UnknownHostException.

try {
    final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
    final String ZIP = "zip";
    final String MODE = "mode";
    final String UNITS = "units";
    final String COUNT = "cnt";
    final String APP_ID = "appid";

    Uri builtUri = Uri.parse(BASE_URL).buildUpon()
                      .appendQueryParameter(ZIP, params[0] + ",in")
                      .appendQueryParameter(MODE,format)
                      .appendQueryParameter(UNITS, units)
                      .appendQueryParameter(COUNT, Integer.toString(numDays))
                      .appendQueryParameter(APP_ID, BuildConfig.OPEN_WEATHER_MAP_API_KEY)
                      .build();
    String str = java.net.URLDecoder.decode(builtUri.toString());
    URL url = new URL(str);

    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("GET");
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);
    urlConnection.connect();

    InputStream inputStream = urlConnection.getInputStream();
    StringBuffer buffer = new StringBuffer();

    if (inputStream == null) {
        return null;
    }

    reader = new BufferedReader(new InputStreamReader(inputStream));

    String line;

    while ((line = reader.readLine()) != null)
        buffer.append(line + "/n");

    if (buffer.length() == 0)
        return null;

    forecastJsonStr = buffer.toString();

    Log.v(LOG_TAG,"JSON forcast string:" +forecastJsonStr);
}catch(SocketTimeoutException e) {
    startActivity(new Intent(getActivity(),CheckNet.class));
} catch (IOException e) {
    Log.e("FetchWeatherTask", "Error:" + e.toString());
    return null;
}

I tested it on my phone running Android version 4.0.4. And while testing I had my mobile data and wifi off


Solution

  • When your mobile data and wifi are turned off, the socket layer is unable to resolve internet addresses (e.g. "openweathermap.org") into an IP address. This is why you get an UnknownHostException.

    Whereas, when you're on a network, and it's able to resolve IP addresses, and the server fails to reply, you will get a SocketTimeoutException.