如何知道何时没有与服务器建立连接?

时间:2013-10-16 19:48:43

标签: android http android-service

我正在使用与我的Android应用程序通信的服务器,安装在智能手机中。该应用程序正在本地环境中使用,它使用计算机的本地IP通过wifi与apache服务器进行通信。

问题是本地ips会不时发生变化,当多次发生这种情况时,由于操作超时,应用程序会因为一些NullPointer异常而崩溃。所以我想知道是否有办法知道连接到服务器的时间是否成功,以及是否有办法(在确认操作超时后)采取一些措施以便应用程序不会冻结。

Thnx提前

我使用此代码进行连接:

HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);


        JSONObject jo = new JSONObject();
        jo.put("tag",tag);




        // Prepare JSON to send by setting the entity
        httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

        // Set up the header types needed to properly transfer JSON
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept-Encoding", "application/json");
        httpPost.setHeader("Accept-Language", "en-US");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();


            is = entity.getContent();

从此最终返回一个jsonObject,然后我解析得到我需要的东西。

2 个答案:

答案 0 :(得分:1)

您需要使用异步任务来执行任何http调用,否则您的应用会冻结直到操作完成:

从简单的sysnc类开始执行您的http请求。 你需要某种处理程序才能得到结果,一旦任务完成,你可以使用用户界面或android handler,我喜欢接口!

class MyHttpTask extends AsyncTask<View, View, String>
{
    String url = null;
    HttpResultHandler handler = null;
            public final static int ERROR_CONNECTION_TIMEOUT = 1000;
            public final static int ERROR_SOCKET_TIMEOUT     = 2000;
            private int error_code = 0;

    public MyHttpTask(String url, HttpResultHandler handler)
    {
        this.url = url;
        this.handler = handler;
    }

    @Override
    protected String doInBackground(View... arg0)
    {
        try
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            JSONObject jo = new JSONObject();
            jo.put("tag", tag);

            // Prepare JSON to send by setting the entity
            httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

            // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            InputStream is = entity.getContent();

            String result = // read your stream as string or any you might prefer byte[]

            return result;
        }
        catch (UnresolvedAddressException e)
        {
            return null;
        }
        catch (UnknownHostException e)
        {
            return null;
        }
            catch (ConnectTimeoutException e)
             {
                    error_code = ERROR_CONNECTION_TIMEOUT;
                    return null;
             }
           catch(SocketTimeoutException e)
            {
                    error_code = ERROR_SOCKET_TIMEOUT;
                    return null;
            }
        catch (IOException e)
        {
            return null;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (result!=null)
        {
            handler.onSuccess(result);
        }
        else
        {
            handler.OnFailure(errorCode);
        }
    }
}

这是一个报告成功或失败操作的简单界面:

static interface HttpResultHandler
{
    public void onSuccess(String result);

    public void OnFailure(int errorCode);
}

测试您的解决方案:

private void testHttpTask()
{
     // here you can block the UI using any type of progress bar
    String url = "http://www.something.com";
    new MyHttpTask(url, new HttpResultHandler()
    {

        @Override
        public void onSuccess(String result)
        {
            // TODO Auto-generated method stub
              // here you get success result
             // dismiss any loading progress bars
        }

        @Override
        public void OnFailure(int error_code)
        {
            // TODO Auto-generated method stub
                    // here you get failure
            // dismiss any loading progress bars, and do your recovery stuff

        }
    }).execute();
}

答案 1 :(得分:0)

将代码放在进行连接的位置。从你描述的内容来看,听起来你需要设置你的http参数,以便你有一个确定的超时,然后抓住它的方式。