【问题标题】:how can i check internet connectivity before executing HTTPClient [duplicate]在执行 HTTPClient 之前如何检查互联网连接 [重复]
【发布时间】:2013-12-30 17:02:52
【问题描述】:

我正在创建 android 应用程序,该应用程序调用我在服务器上创建的 rest 服务,并且服务器正在运行,但由于互联网连接问题,有时我的应用程序运行成功,但有时它崩溃了。我的连接类的代码是

public class CommunicationClass {

@SuppressWarnings("unused")
private static final String TAG = null;
public String Domain;
public HttpClient client;
public HttpPost datapost;
public HttpResponse response;
public BufferedReader reader;
public StringBuilder builder;
public JSONTokener tokener;
public JSONObject finalResult;
List<NameValuePair> namevaluepairs = new ArrayList<NameValuePair>(10);


public void setClient() {
    // TODO Auto-generated method stub
    client = new DefaultHttpClient();
    System.out.println("Created http client");
}
public void setDomain(String st) {
    // TODO Auto-generated method stub
    Domain = st;
    System.out.println("Domain has been set");
}
public void setResponse(){
    response=null;
    System.out.println("Response has been initalized by null");
}
public void setStringBuilder(){
    builder = new StringBuilder();
}
public void setreader(){
    try {
        reader = new BufferedReader(new InputStreamReader(this.response.getEntity().getContent(), "UTF-8"));
        System.out.println("Setting the contents of the Reader");
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        System.out.println("In the UnsupportedEncodingException catch of the Reader");
        e.printStackTrace();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        System.out.println("In the IllegalStateException catch of the Reader");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        System.out.println("In the IOException catch of the Reader");
        e.printStackTrace();
    }

}
public void startpost(String str){
    datapost=new HttpPost(str);
    System.out.println("Created the httppost domain");
}
public void insertdata(String tag,String value){
    namevaluepairs.add(new BasicNameValuePair(tag,value));
    System.out.println("Added the parameter  "+tag);
}
public void trydata(){
    try {
        this.datapost.setEntity(new UrlEncodedFormEntity(this.namevaluepairs));
        System.out.println("Setting the entity");
        try {
            this.response = this.client.execute(this.datapost);
            System.out.println("executing the client");
             if(this.response != null){
                 System.out.println("i am in if of this.response!=null");
             }
             else{
                 System.out.println("i am in else of this.response!=null");
             }
             System.out.println("in response try box");
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            System.out.println("in ClientProtocolException Catch box");
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("in IOException Catch box");
            e.printStackTrace();
        }
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        System.out.println("in UnSupported Catch box");
        e.printStackTrace();
    }
}
public void readresponse(){     



    try {
        for (String line = null; (line = reader.readLine()) != null;) {
            builder.append(line).append("\n");

        }
        System.out.println(this.builder);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     tokener = new JSONTokener(builder.toString());
    try {
         finalResult = new JSONObject(tokener);
        System.out.println("I am in try block of json final result reading");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        System.out.println("I catch block of jsonException");
        e.printStackTrace();
    } 
}


}

它在 trydata() 行上给了我错误;实际执行 HTTP 客户端,所以我想确保它不应该由于互联网连接而崩溃,但可能会抛出可以捕获或烤面包的异常。伙计们需要这方面的帮助

谢谢!

【问题讨论】:

  • 我在启动应用程序之前检查了互联网连接如果互联网不可用,它将启动但不会工作我问为什么它在 trydata() 崩溃;这实际上是在执行客户端它显示在 logcat 中设置实体,然后出现一长串红色错误为什么它会崩溃????

标签: java android androidhttpclient


【解决方案1】:
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager 
          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

别忘了:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

这对我来说很好用。

【讨论】:

    【解决方案2】:

    在调用 Webservice 之前检查 Internet 连接:

     public static boolean isNetworkAvailable(Context context) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetworkInfo = connectivityManager
                    .getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
    

    【讨论】:

      【解决方案3】:

      虽然其他答案是正确的,但它们是部分正确的。如果您想知道您有互联网连接,而不仅仅是连接到 Wi-Fi 热点,您必须 ping 一个站点。 This 是我昨天发现的,如果您已连接但没有通过此热点连接互联网,则可以使用。基本上它 ping 谷歌。对其使用布尔值,并将其放入其他人答案的检查中。

      【讨论】:

        【解决方案4】:

        使用这个:

        public static Boolean checkForInternetConnection(Context context) {
            final ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
            if (activeNetwork != null && activeNetwork.isConnected()) {
                return true;
            } else {
                return false;
            }
        
        }
        

        【讨论】:

        • 这条线检查互联网连接我在应用程序启动后立即检查它检查互联网连接,如果互联网连接,那么应用程序将工作,否则我不会说我有一个用户刚刚登录,他有互联网连接,当他从一个房间移动到另一个房间时,这个应用程序会登录,但不会调用服务器上的编辑方法,但会崩溃,为什么它会由于客户端执行而崩溃。
        猜你喜欢
        • 1970-01-01
        • 2017-11-30
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-04-03
        • 2013-08-16
        相关资源
        最近更新 更多