如何知道连接未建立到服务器?

问题描述:

我正在使用与安装在智能手机上的我的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,这事后我分析得到我所需要的。

你需要使用异步任务做任何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(); 
} 
+0

我已经使用了异步任务,我连接代码,在一个单独的文件上实现。我想你正试图给我一种处理错误的方法,但我想我不明白这是怎么回事。我的主要问题是,我用什么对象来处理超时状态,以便我可以操纵它。 – user1732457

+0

对于每种类型的异常都有一个原因,对于ConnectTimeoutException意味着连接到服务器的尝试超时。并且对于SocketTimeoutException表示与服务器的连接超时。我已经更新了代码,以便在失败的情况下返回错误代码,现在当您发现错误是由于超时造成的,然后执行额外的代码,例如重试连接。 –

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