okHttp封装

package com.mkyl.yizhengapp.model.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils<T> {

    public final int CONNECT_TIMEOUT = 60;
    public final int READ_TIMEOUT = 100;
    public final int WRITE_TIMEOUT = 60;
    private BaseCallBack callBack;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    callBack.success(msg.obj);
                    break;
                case 1:
                    callBack.err(500, (String) msg.obj);
                    break;
            }
        }
    };

    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.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;
    }

    //get请求
    public <T> void getLoadNet(String url, BaseCallBack callBack, final Class<T> tClass) {
        this.callBack = callBack;
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = e.getMessage().toString();
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Gson gson = new Gson();
                T t = gson.fromJson(string, tClass);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        });
    }

    //post请求
    public <T> void getToken(String url, Map<String, Object> map, BaseCallBack callBack, final Class<T> tClass) {
        this.callBack = callBack;
        RequestBody requestBody;
        if (map == null) {
            map = new HashMap<>();
        }
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        FormBody.Builder builder = new FormBody.Builder();
        for (Map.Entry<String, Object> map1 : map.entrySet()) {
            String key = map1.getKey();
            String value;
            if (map1.getValue() == null) {
                value = "";
            } else {
                value = (String) map1.getValue();
            }
            builder.add(key, value);
        }
        requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        //new call
        Call call = mOkHttpClient.newCall(request);
        //请求加入调度
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = e.getMessage().toString();
                handler.sendMessage(msg);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("onResponse", "onResponse: " + string);
                Gson gson = new Gson();
                T t = gson.fromJson(string, tClass);
                Message msg = Message.obtain();
                msg.what = 0;
                msg.obj = t;
                handler.sendMessage(msg);
            }
        });
    }
}
 2.baseCallback:
package com.mkyl.yizhengapp.model.utils;
public interface BaseCallBack<T> {
    void success(T t);//成功
    void err(int code, String er);//失败
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值