Android 对OkHttp做简单的封装,并实现了获取Json数据的自动转换

OkHttp封装代码

package com.diabin.minda.http;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;


public class OkHttpHelper {

    private static OkHttpClient okHttpClient;

    private Gson gson;

    private Handler handler;

    //OkHttpHelper的构造方法
    private OkHttpHelper(){

        okHttpClient = new OkHttpClient();
        okHttpClient.setReadTimeout(10,TimeUnit.SECONDS);
        okHttpClient.setWriteTimeout(10,TimeUnit.SECONDS);
        okHttpClient.setConnectTimeout(10,TimeUnit.SECONDS);

        gson = new Gson();
        handler = new Handler(Looper.getMainLooper());

    };

    //构建一个OkHttpHelper实例
    public static OkHttpHelper getInstance(){

        return new OkHttpHelper();
    }

    //Get方法
    public void get(String url,BaseCallback callback){

        Request request = buildRequest(url,null,HttpMethodType.GET);
        doRequest(request,callback);
    }

    //Post方法
    public void post(String url, Map<String,String> params,BaseCallback callback){

        Request request = buildRequest(url,params,HttpMethodType.POST);
        doRequest(request,callback);
    }

    //构建Request的方法
    private  Request buildRequest(String url,Map<String,String> params,HttpMethodType methodType){

        //构建一个Request的对象
        Request.Builder builder = new Request.Builder();
        builder.url(url);

        if (methodType == HttpMethodType.GET){
            builder.get();
        }
        else if (methodType == HttpMethodType.POST){

            RequestBody body = buildFormData(params);
            builder.post(body);
        }
        return builder.build();
    }

    //构建RequestBody的方法
    private RequestBody buildFormData(Map<String,String> params){

        FormEncodingBuilder builder = new FormEncodingBuilder();

        if (params != null){
            //循环取出Map中的数据
            for (Map.Entry<String,String> entry :params.entrySet()){
                builder.add(entry.getKey(),entry.getValue());
            }
        }
        return builder.build();
    }

    //用来回调的方法
    private void callbackSuccess(final BaseCallback callback,final Response response,final Object object){

        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onSuccess(response,object);
            }
        });
    }

    //实现一个枚举类,用来判断使用Get方法还是使用Post方法
    enum HttpMethodType{
        GET,
        POST
    }

    //传入自定义的Callback
    public void doRequest(Request request, final BaseCallback callback){

        //在请求前调用这个方法,用来弹出Loading对话框或者做其他处理
        callback.onRequestBefore(request);

        okHttpClient.newCall(request).enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {

                callback.onFailure(request,e);
            }

            @Override
            public void onResponse(Response response) throws IOException {

                callback.onResponse(response);

              if (response.isSuccessful()){
                  String resultStr = response.body().string();
                  //如果原本需要的类型就是String则直接返回,否则进行转换
                  if (callback.mType == String.class){
//                      callback.onSuccess(response,resultStr);
                      callbackSuccess(callback,response,resultStr);
                  }else
                  {
                      //使用try catch处理json解析错误
                      try {
                          Object object = gson.fromJson(resultStr,callback.mType);
                          callbackSuccess(callback,response,object);
                      }catch (JsonParseException e){
                          callback.onError(response,response.code(),e);
                      }
                  }

              }
              else{
                  callback.onError(response,response.code(),null);
              }
            }
        });
    }
}

实现自动类型转换的代码

package com.diabin.minda.http;

import com.google.gson.internal.$Gson$Types;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseCallback<T> {

    public Type mType;
    //将泛型 T 转换成 mType
    static Type getSuperclassTypeParameter(Class<?> subclass){
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class){
            throw new RuntimeException("Missing type parameter");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);

    }

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

    //请求前调用的方法
    //定义抽象方法给子类实现
    public abstract void onRequestBefore(Request request);

    public abstract void onFailure(Request request, IOException e);

    public abstract void onResponse(Response response);


    public abstract void onSuccess (Response response,T t);

    //code是http的状态码,用来提示信息
    public abstract void onError (Response response,int code,Exception e);
}

使用的方法

//生成一个http实例
private OkHttpHelper httpHelper = OkHttpHelper.getInstance();
//这里的“List”就可以替换成自己想要的类型了,“HomeCampaign”是你封装的类对象
httpHelper.get(Contants.API.CAMPAIGN_HOME, new BaseCallback<List<HomeCampaign>>() {
            @Override
            public void onRequestBefore(Request request) {

                System.out.println("onRequestBefore");
            }

            @Override
            public void onFailure(Request request, IOException e) {

                System.out.println("onFailure");
            }

            @Override
            public void onResponse(Response response) {
                System.out.println("onResponse");

            }

            @Override
            public void onSuccess(Response response, List<HomeCampaign> homeCampaigns) {

                System.out.println("onSuccess");
                initData(homeCampaigns);
            }


            @Override
            public void onError(Response response, int code, Exception e) {
                System.out.println("onError");


            }
        });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值