Android OkHttp的封装

来源:互联网 发布:数据库管理证书 编辑:程序博客网 时间:2024/05/16 19:13
下面是我对OkHttp的get和post网络请求方法进行的一个封装,方便使用!
package http;import android.os.Handler;import android.util.Log;import java.io.IOException;import java.util.Map;import http.callback.Callback;import okhttp3.Call;import okhttp3.FormBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;/** * Created by ZhangTAO on 2017/11/9. */public class HttpUtils {    private static volatile HttpUtils instance;    private static final String TAG = "HttpUtils";    public static Handler ler = new Handler();    private HttpUtils() {}    /**     * 双重检测锁-单例模式     * @return     */    public static HttpUtils getInstance() {        if(instance == null) {            synchronized (HttpUtils.class) {                if (instance == null) {                    instance = new HttpUtils();                }            }        }        return instance;    }    /**     * @网络请求--get请求     */    public void get(String url, Map<String,String> map, final Callback callback, final Class cls) {         //对url和参数做一下拼接处理        StringBuffer sb = new StringBuffer();        sb.append(url);        if(url.contains("?")) {            //如果?不在最后一位            if(sb.indexOf("?") != sb.length()-1) {                sb.append("&");            }        }else {            sb.append("?");        }        for (Map.Entry<String, String> entry : map.entrySet()) {            sb.append(entry.getKey())                    .append("=")                    .append(entry.getValue())                    .append("&");        }        if(sb.indexOf("&") != -1) {            sb.deleteCharAt(sb.lastIndexOf("&"));        }        Log.i(TAG, "get url: " + sb);        //new 一个OkHttpClient对象        OkHttpClient client = new OkHttpClient();        Request request = new Request.Builder()                .get()                .url(sb.toString())                .build();        Call call = client.newCall(request);        call.enqueue(new okhttp3.Callback() {            @Override            public void onFailure(Call call, final IOException e) {                Log.e(TAG,"onFailure:"+ e.getCause().getStackTrace() + e.getMessage());                ler.post(new Runnable() {                    @Override                    public void run() {                       callback.onFailure(e);                    }                });            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String result = response.body().string();                final Object o = GsonUtils.getInstance().fromJson(result, cls);                ler.post(new Runnable() {                    @Override                    public void run() {                        callback.onSuccess(o);                    }                });            }        });    }    /**     * @网络请求--post请求     */    public void post(String url, Map<String,String> map, final Callback callback, final Class cls) {        OkHttpClient client = new OkHttpClient();        FormBody.Builder builder = new FormBody.Builder();        for(Map.Entry<String,String> entry:map.entrySet()) {            builder.add(entry.getKey(),entry.getValue());        }        FormBody formBody = builder.build();        Request request = new Request.Builder()                .url(url)                .post(formBody)                .build();        Call call = client.newCall(request);        call.enqueue(new okhttp3.Callback() {            @Override            public void onFailure(Call call, final IOException e) {                Log.e(TAG,"onFailure:"+e.getCause().getStackTrace() + e.getMessage());                ler.post(new Runnable() {                    @Override                    public void run() {                        callback.onFailure(e);                    }                });            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String result = response.body().string();                final Object o = GsonUtils.getInstance().fromJson(result, cls);                ler.post(new Runnable() {                    @Override                    public void run() {                        callback.onSuccess(o);                    }                });            }        });    }}
上面的get和post方法种的参数Callback是自定义的一个接口,用于把数据调用。
package com.bwie.mvpokrecyclerview.callback;/** * Created by WuXirui * Create Time: 2017/11/9 * Description: */public interface CallBack {    void onSuccess(String tag, Object o);    void onFailed(String tag, Exception e);}
方法中的Class参数是Bean包,用于Gson的解析字符串。
package http;import com.google.gson.Gson;/** * Created by ZhangTAO on 2017/11/9. */public class GsonUtils {    private static volatile Gson gson;    public static Gson getInstance() {        if(gson == null) {            gson = new Gson();        }        return gson;    }}

下面是一个应用拦截器

/**     * 应用拦截器     */    public class LoggingInterceptor implements Interceptor {        @Override        public Response intercept(Chain chain) throws IOException {            Request original = chain.request();            HttpUrl url=original.url().newBuilder()                    .addQueryParameter("source","android")                    .build();            //添加请求头            Request request = original.newBuilder()                    .url(url)                    .build();            return chain.proceed(request);        }    }

给请求网络添加拦截器:

OkHttpClient client = new OkHttpClient.Builder()      .addInterceptor(new LoggingInterceptor())      .build();

以上就是对OkHttp的封装,希望可以帮到大家!!!


原创粉丝点击