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

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

谢谢!

最佳答案

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

这对我来说很棒。

关于java - 我如何在执行 HTTPClient 之前检查互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20540895/

相关文章:

java - 无法解析符号 'R'

android - newMyFriendsRequest Facebook 仅返回 25 个好友

java - 从 AndroidHttpClient 迁移到 URLConnection

java - 为什么 Eclipse Export -> Executable Jar 不提供要包含的类的选择?

java - 我们如何在自定义标签中使用现有的标签库功能?

android - 单击按钮即可发现蓝牙,无需导航至蓝牙设置页面

android - 来自 Android 的大量 HTTP 请求导致网络断开。如何解决这个问题?

java - 如何在 spring security 中检查每个请求的用户状态

java - "No Persistence Unit Found"错误

android - 我可以用什么替换 http 弃用的方法?