okHttp封装

来源:互联网 发布:大数据用什么数据库 编辑:程序博客网 时间:2024/06/16 18:45
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);//失败}

原创粉丝点击