请求网络连接工具类

判断是否有网络连接

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.test.administrator.myproject.BaseApplication;

/** * Created by Administrator on 2015/10/10. */
public class NetConnectUtils {
    public static boolean isNetConnect() {
        //BaseApplication.getmBaseApplication()传入上下文
        ConnectivityManager cm = (ConnectivityManager) BaseApplication.getmBaseApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
        } else {
            //如果仅仅是用来判断网络连接
            //则可以使用 cm.getActiveNetworkInfo().isAvailable();
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}

向服务器请求网络,这里以Volley为例

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.test.shiweiwei.myproject.BaseApplication;
import com.test.shiweiwei.myproject.utils.NetConnectUtils;
import java.util.HashMap;
import java.util.Map;

/** * Created by Administrator on 2015/10/10. */
public class MyNetConnection {
    /** * 采用单例进行网络连接 */
    //私有构造器
    private MyNetConnection(){

    }
    //设置静态属性
    private static MyNetConnection mMyNetConncetion;
    //设置公有访问方法
    public static MyNetConnection newInstance(){
        if (mMyNetConncetion==null){
            mMyNetConncetion=new MyNetConnection();
        }
        return mMyNetConncetion;
    };
    //利用观察者模式,监听网络连接
    public interface OnHTTPConnectionListener{
        //连接成功
        public void onSuccess(String response);
        //连接失败
        public void onError(int errorCode);
        //无网络连接
        public void onNoNet();
    }
    public void addRequest(String url, final HashMap<String,String> params,final OnHTTPConnectionListener onHttpConnectionListener){
        //判断是否有网络连接
        if (!NetConnectUtils.isNetConnect()){
            onHttpConnectionListener.onNoNet();
            return;
        }
        //下面选择一种连接网络的方式,这里使用Volley

        //RequestQueue是一个请求队列对象,它可以缓存所有的HTTP请求,然后按照一定的算法并发地发出这些请求.
        RequestQueue queue= Volley.newRequestQueue(BaseApplication.getmBaseApplication());

        StringRequest request=new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                onHttpConnectionListener.onSuccess(response);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error.networkResponse==null){
                    onHttpConnectionListener.onError(404);
                }else {
                    onHttpConnectionListener.onError(error.networkResponse.statusCode);
                }
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return params;
            }
        };
        //将这个StringRequest对象添加到RequestQueue里面
        queue.add(request);
    }
}

你可能感兴趣的:(网络连接)