-2

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

Markus Safar
  • 5,899
  • 5
  • 25
  • 41
Saran Sankaran
  • 1,835
  • 2
  • 17
  • 30
  • [Official docs](https://docs.oracle.com/javase/7/docs/api/java/net/UnknownHostException.html). You have invalid IP (URL). I don't sure that it can be reason of error but check your manifest permissions for net if address is valid. – Шах Feb 06 '16 at 21:00
  • try BASE_URL = "http://192.241.169.168/data/2.5/forecast/daily?" instead and see if it helps – Pooya Feb 06 '16 at 21:02
  • I am trying to get SocketTimeOutExcepetion. I know i will not be able to connect to the host because I had my mobile data and my wifi off – Saran Sankaran Feb 06 '16 at 21:03
  • No, you cannot get this error without server access. Because app must send request to server and doesn't get answer package from it. – Шах Feb 06 '16 at 21:06
  • Sorry for my English. – Шах Feb 06 '16 at 21:07
  • You should read about TCP/IP connection to understand why you cannot get this error. – Шах Feb 06 '16 at 21:09
  • @Pooya this is the output what i get from logcat Error:java.net.ConnectException: failed to connect to /192.241.169.168 (port 80) after 5000ms: connect failed: ENETUNREACH (Network is unreachable) – Saran Sankaran Feb 06 '16 at 21:13
  • well... of course the "network is unreachable"... you're not on a network! (see my answer) – Dmitry Brant Feb 06 '16 at 21:21

2 Answers2

3

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.

Dmitry Brant
  • 7,299
  • 2
  • 27
  • 45
0

If you want to simulate the exception do the following:

  1. Disconnect your data and connect your Wi-Fi
  2. Edit your setting of your Wi-Fi connection
  3. Change to static IP and put 169.254.0.50 for IP, 255.255.0.0 for subnet and 169.254.0.1 for gateway
  4. Change the BASE_URL = "192.241.169.168/data/2.5/forecast/daily?"
  5. Run your app
Pooya
  • 5,593
  • 3
  • 19
  • 41
  • In my connection setting I have IP, Gateway, Network prefix length, DNS1 & 2. I set as IP and Gateway as per your suggestion. And made change to the URL but it give me this in my logcat Error:java.net.SocketException: failed to connect to /192.241.169.168 (port 80) after 5000ms: isConnected failed: EHOSTUNREACH (No route to host) – Saran Sankaran Feb 06 '16 at 21:41
  • it is trying to connect for 5000ms but is not giving the SocketTimeoutException but as per android doc [android doc](http://developer.android.com/reference/java/net/URLConnection.html#setConnectTimeout(int))it says it should give a SocketTimeoutException if it fails to connect – Saran Sankaran Feb 06 '16 at 21:46
  • @SaranSankaran you want to see how your programs react under that situation? – Pooya Feb 07 '16 at 02:05
  • I had a misconception about SocketTimeoutException. I was thinking it would work even no Internet. – Saran Sankaran Feb 07 '16 at 20:05