如何在执行HTTPClient之前检查互联网连接

时间:2013-12-12 10:26:49

标签: java android androidhttpclient

我正在创建Android应用程序,调用我在服务器和服务器上制作的休息服务正在重新运行,但是由于互联网连接问题,我的应用程序运行成功但有时它会崩溃。我的连接类的代码是

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客户端所以我想确保它不会因为互联网连接而崩溃,但可能会抛出可以捕获的异常或吐司。伙计们需要帮助

谢谢!

4 个答案:

答案 0 :(得分:3)

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" />

它对我很有用。

答案 1 :(得分:1)

在调用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();
    }

答案 2 :(得分:1)

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

答案 3 :(得分:0)

使用此:

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;
    }

}