String urlStr = "nana.com/nana/api/v1"
HttpURLConnection conn = null;
BufferedReader rd = null;
StringBuilder sb = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
else {
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
}
} catch (IOException i) {
i.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
如果服务器处于活动状态并且正在工作,则此代码对我有用,但是当我关闭服务器时,它会超时并“意外”崩溃。我想要的只是应用程序在服务器无法访问时说出或显示警报对话框。这是我的日志:
09-14 11:52:57.702: E/AndroidRuntime(17256): at android.os.Handler.dispatchMessage(Handler.java:99)
09-14 11:52:57.702: E/AndroidRuntime(17256): at android.os.Looper.loop(Looper.java:130)
09-14 11:52:57.702: E/AndroidRuntime(17256): at android.app.ActivityThread.main(ActivityThread.java:3693)
09-14 11:52:57.702: E/AndroidRuntime(17256): at java.lang.reflect.Method.invokeNative(Native Method)
09-14 11:52:57.702: E/AndroidRuntime(17256): at java.lang.reflect.Method.invoke(Method.java:507)
09-14 11:52:57.702: E/AndroidRuntime(17256): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
09-14 11:52:57.702: E/AndroidRuntime(17256): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
09-14 11:52:57.702: E/AndroidRuntime(17256): at dalvik.system.NativeStart.main(Native Method)
09-14 11:52:57.742: E/(179): Dumpstate > /data/log/dumpstate_app_error