封装OkHttp3框架

okHttp3是一种非常好用的请求框架,我们可以进行简易封装,然后就可以通调用进行网络请求
这里还使用了网络拦截器,用来查看请求与返回的数据,
需要依赖的是:compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'




public class HttpUtil {

    private static volatile HttpUtil httpUtil;
    private Context context;
    private OkHttpClient client;
    private Handler handler = new Handler(Looper.getMainLooper());

    public HttpUtil(Context context) {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
        this.context = context;
        client = new OkHttpClient.Builder()
                .addInterceptor(logging)
                .build();
    }

    public static HttpUtil getinstance(Context context){
        if(httpUtil==null){
            synchronized (HttpUtil.class){
                if(httpUtil == null){
                   httpUtil = new HttpUtil(context);

                }
            }

        }
        return httpUtil;
    }




    public void doGet(String url, final Class clazz, final OnNetListener onNetListener){
        if(url!=null){
            Request request = new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {


                @Override
                public void onFailure(Call call, IOException e) {
                        onNetListener.onError(e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String string = response.body().string();

                    Gson gson = new Gson();
                    final basebean b = (basebean) gson.fromJson(string, clazz);
                    String code = b.getCode();
                    if(code.equals("0")){
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    onNetListener.onSuccess(b);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    else if(code.equals("1")){

                    }
                    else{

                    }

                }
            });
        }



    }

    public void doPost(String url, Map<String,String> params, final Class clazz, final OnNetListener onNetListener){

        if(url!=null&&params!=null&&params.size()>0){

            FormBody.Builder builder = new FormBody.Builder();

            for (Map.Entry<String,String > entry:params.entrySet()){
                builder.add(entry.getKey(),entry.getValue());
            }

            FormBody formBody = builder.build();

            Request request = new Request.Builder().url(url).post(formBody).build();

            client.newCall(request).enqueue(new Callback() {


                @Override
                public void onFailure(Call call, IOException e) {
                    onNetListener.onError(e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String string = response.body().string();

                    Gson gson = new Gson();
                    final basebean b = (basebean) gson.fromJson(string, clazz);
                    String code = b.getCode();
                    if(code.equals("0")){
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    onNetListener.onSuccess(b);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                    else if(code.equals("1")){

                    }
                    else{

                    }

                }
            });

        }
    }



}

这里边的OnNetListener是一个自定义的接口,我们可以进行接口回调
public interface OnNetListener {
    public void onError(IOException e);
    public void onSuccess(basebean b) throws IOException;
}
basebean是所有bena类的父类,所以可以通过传入要请求数据的专有的bean.class,实现接口回调,


这个项目还可以加入网络判断,这是网络判断的类:
package utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;



public class NetWorkUtil {
    // check all network connect, WIFI or mobile
    public static boolean isNetworkAvailable(final Context context) {
        boolean hasWifoCon = false;
        boolean hasMobileCon = false;

        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfos = cm.getAllNetworkInfo();
        for (NetworkInfo net : netInfos) {

            String type = net.getTypeName();
            if (type.equalsIgnoreCase("WIFI")) {
                if (net.isConnected()) {
                    hasWifoCon = true;
                }
            }

            if (type.equalsIgnoreCase("MOBILE")) {
                if (net.isConnected()) {
                    hasMobileCon = true;
                }
            }
        }
        return hasWifoCon || hasMobileCon;

    }
}

这么使用:

if(!NetWorkUtil.isNetworkAvailable(context)){
    Toast.makeText(context,"没有网络,请查看设置",Toast.LENGTH_SHORT).show();
    return;
}




 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值