okHttp二次封装

package com.example.diynsg.net;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.example.diynsg.bean.BaseBean;
import com.example.diynsg.utils.NetWorkUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

/**
 * Created by zwj on 2017/10/1.
 */

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

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

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

    public void doPost(String url, Map<String, String> params, final Class clazz, final OnNetListener onNetListener) {
        //网络判断
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
            return;
        }
        if (params != null && params.size() > 0) {
            FormBody.Builder builder = new FormBody.Builder();
            params.put("client", "android");
            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) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final BaseBean baseBean = (BaseBean) new Gson().fromJson(response.body().string(), clazz);
                    int code = baseBean.getCode();
                    if (code == 200) {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    onNetListener.onSuccess(baseBean);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                    } else if (code == 400) {

                    } else if (code == 300) {

                    }
                }
            });
        }


    }

    public void doGet(String url, final Class clazz, final OnNetListener onNetListener) {

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


        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onError(e);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                final BaseBean beseBean = (BaseBean) new Gson().fromJson(string, clazz);
                int code = beseBean.getCode();
                if (code == 200) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                onNetListener.onSuccess(beseBean);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                } else if (code == 400) {

                } else if (code == 300) {

                }
            }
        });

    }

    /**
     * @param url
     * @param params
     * @param header
     * @param clazz
     * @param onNetListener
     */


    public void doGet(String url, HashMap<String, String> params, HashMap<String, String> header, final Class clazz, final OnNetListener onNetListener) {
        //网络判断
        if (!NetWorkUtil.isNetworkAvailable(context)) {
            Toast.makeText(context, "没有网络,请查看设置", Toast.LENGTH_SHORT).show();
            return;
        }

        Request.Builder builder = new Request.Builder();
        StringBuilder sb = new StringBuilder();
        if(params!=null){

            for (Map.Entry<String, String> entry : params.entrySet()) {
                sb.append(url);
                sb.append("?");
                sb.append(entry.getKey());
                sb.append("=");
                sb.append(entry.getValue());
            }
            String finalUrl = sb.toString();
            builder.url(finalUrl);

        }else{
            builder.url(url);
        }


        //添加请求头
        if (header!=null) {
            if (params != null && header.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.addHeader(entry.getKey(), entry.getValue());
                }
            }
        }
        final Request request = builder.build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        onNetListener.onError(e);
                    }
                });

            }

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

                final BaseBean baseBean = (BaseBean) new Gson().fromJson(string, clazz);
                int code = baseBean.getCode();
                if (code == 200) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                onNetListener.onSuccess(baseBean);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

                } else if (code == 400) {

                } else if (code == 300) {

                }
            }
        });
    }

}

//OnNetListener类
package com.example.diynsg.net;

import com.example.diynsg.bean.BaseBean;

import java.io.IOException;

/**
 * Created by zwj on 2017/10/10.
 */

public interface OnNetListener {
    public void onSuccess(BaseBean baseBean) throws IOException;

    public void onError(IOException e);
}

//网络判断类
package com.example.diynsg.utils;

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

/**
 * Created by zwj on 2017/10/1.
 * 检查wifi 和 mobile
 */

public class NetWorkUtil {

    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 typeName = net.getTypeName();
            if (typeName.equalsIgnoreCase("WIFI")){
                if (net.isConnected()){
                    hasWifoCon=true;
                }
            }
            if (typeName.equalsIgnoreCase("MOBILE")){
                if (net.isConnected()){
                    hasMobileCon=true;
                }
            }
        }
        return hasWifoCon || hasMobileCon;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值