1
            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
4

1 回答 1

0

请尝试以下

public String getData(String url) {

    HttpClient httpclient = new DefaultHttpClient(SetHttpParams.setHttp(
            50000, 50000));

    HttpGet httpget = new HttpGet(url);
    HttpResponse response;

    try {
        response = httpclient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == 200) {
            org.apache.http.HttpEntity entity = response.getEntity();
            if (entity != null) {

                InputStream instream = entity.getContent();

                String res = Functions.convertStreamToString(instream);
            }
        }
    } catch (ConnectTimeoutException e) {
    } catch (SocketTimeoutException e) {
    } catch (IOException ex) {
    }
}

字符串 res 是将存储响应的字符串。在 Asyntasks doinBackground() 方法中调用上述函数。放置一些本地布尔变量来检查是否发生异常。如果发生异常或继续您的工作,则在 onPostExecute() 中显示对话框。希望它可以帮助你。

于 2013-09-14T09:45:31.480 回答