我是 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;
}
我在运行 Android 版本 4.0.4 的手机上对其进行了测试。在测试时,我关闭了移动数据和 wifi