获取 UnknownHostException 而不是 SocketTimeOutExcepetion

Getting UnknownHostException instead of SocketTimeOutExcepetion

我是 android 和 Java 的新手。我正在尝试从 UDACITY 学习 android 应用程序开发。我正在尝试 运行 这段代码,我期待 SocketTimeOutExcepetion 但我得到的是 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;
}

我在我的 phone 运行ning Android 版本 4.0.4 上测试了它。在测试时,我关闭了移动数据和 wifi

当您的移动数据和 wifi 关闭时,套接字层无法将互联网地址(例如 "openweathermap.org")解析为 IP 地址。这就是您收到 UnknownHostException 的原因。

然而,当您在网络上时,它能够解析 IP 地址,而服务器无法回复,您将收到 SocketTimeoutException。

如果要模拟异常,请执行以下操作:

  1. 断开数据连接并连接 Wi-Fi
  2. 编辑您的 Wi-Fi 连接设置
  3. 更改为静态 IP,IP 为 169.254.0.50,子网为 255.255.0.0,网关为 169.254.0.1
  4. 更改BASE_URL = "192.241.169.168/data/2.5/forecast/daily?"
  5. 运行 你的应用程序