OkHttp异步加载数据使用单利模式

package com.bawei.test;
import com.google.gson.Gson;
import com.google.gson.internal.$Gson$Types;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * 使用单例设计模式对OkHttp进行封装
 */

public class OkHttp {
    private final Gson gson;
    private volatile static OkHttp okHttpManager;
    private   OkHttpClient okHttpClient;
    private  Request request;
    private OkHttp(){
        gson = new Gson();
    }
    public  static OkHttp getInstance(){
        if (okHttpManager == null) {
            synchronized (OkHttp.class) {
                if (okHttpManager == null) {
                    okHttpManager = new OkHttp();
                }
            }
        }
        return okHttpManager;
    }
    private boolean setRequest=false;
    private boolean setOkHttpClient=false;
    public OkHttp setRequest(Request request) {
        this.request = request;
        setRequest=true;
        return this;
    }

    public OkHttp setOkHttpClient(OkHttpClient okHttpClient) {
        this.okHttpClient = okHttpClient;
        setOkHttpClient=true;
        return this;
    }

    public  void requestAsyn(String url, Map map, final ResultCallback mcallBack){
        if (setRequest==false) {
            request = getRequest(url, map);
        }
        if (setOkHttpClient==false&&okHttpClient==null)
        {
           //连接器
        okHttpClient= new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
        }
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mcallBack.onFailure(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response!=null&&response.isSuccessful()) {
                    String json = response.body().string();
                    mcallBack.onResponse(call, gson.fromJson(json, mcallBack.mType), json);
                }
            }
        });
        if (setRequest){
            request=null;
            setRequest=false;
        }
        if (setOkHttpClient) {
            okHttpClient = null;
            setOkHttpClient=false;
        }

    }
    public void UpLoadFile(String url, Map map, final ResultCallback mcallBack){
        if (map==null||map.size()<1)
            throw new RuntimeException("上传头像必须用post方式,map集合不能为空");
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        for (Map.Entry stringObjectEntry : map.entrySet()) {
            String key = stringObjectEntry.getKey();
            Object value = stringObjectEntry.getValue();
            if (value instanceof File){//如果请求的值是文件
                File file = (File) value;
                builder.addFormDataPart(key,((File) value).getName(), RequestBody.create(MediaType.parse("application/octet-stream"),file));
            }else{//如果请求的值是string类型
                builder.addFormDataPart(key,value.toString());
            }
        }
        Request request = new Request.Builder().post(builder.build()).url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mcallBack.onFailure(call,e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response!=null&&response.isSuccessful()) {
                    String json = response.body().string();
                    mcallBack.onResponse(call, gson.fromJson(json, mcallBack.mType), json);
                }
            }
        });
    }

    private Request getRequest(String url, Map map) {
        Request request;
        if (map==null||map.size()==0){
            request =new Request.Builder().get().url(url).build();
        }
        else {
            FormBody.Builder builder = new FormBody.Builder();
            for (Map.Entry stringStringEntry : map.entrySet()) {
                builder.add(stringStringEntry.getKey(),stringStringEntry.getValue());
            }
            FormBody build = builder.build();
            request =new Request.Builder().post(build).url(url).build();
        }
        return request;
    }
    public static abstract class ResultCallback<T>
    {
        Type mType;

        public ResultCallback()
        {
            mType = getSuperclassTypeParameter(getClass());
        }

        static Type getSuperclassTypeParameter(Class subclass)
        {
            //通过反射得到泛型参数
            //Type是 Java 编程语言中所有类型的公共高级接口。它们包括原始类型、参数化类型、数组类型、类型变量和基本类型。
            Type superclass = subclass.getGenericSuperclass();
            if (superclass instanceof Class)
            {
                throw new RuntimeException("Missing type parameter.");
            }
            //ParameterizedType参数化类型,即泛型
            ParameterizedType parameterized = (ParameterizedType) superclass;
            //getActualTypeArguments获取参数化类型的数组,泛型可能有多个
            //将Java 中的Type实现,转化为自己内部的数据实现,得到gson解析需要的泛型
            return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
        }

        public abstract void onFailure(Call call, IOException e);
        public abstract void onResponse(Call call,T response,String json);
    }


}

你可能感兴趣的:(OkHttp异步加载数据使用单利模式)