0

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

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

提前谢谢

我使用此代码进行连接:

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,然后我解析得到我需要的东西。

4

2 回答 2

1

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

从简单的 sysnc 类开始执行您的 http 请求。您还需要某种处理程序来获取结果,一旦任务完成,您可以使用用户界面或 android处理程序,我喜欢界面!

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();
}
于 2013-10-16T21:12:39.893 回答
0

把你的代码放在你建立连接的地方。从你的描述听起来你需要设置你的 http 参数,以便你有一个确定的超时,然后以某种方式捕捉它。

于 2013-10-16T19:54:53.573 回答