欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android OKHTTP的单例和再封装的实例

程序员文章站 2024-01-20 21:29:58
android okhttp的单例和再封装的实例 /** * created by zm on 16-2-1 * okhttp的再封装,对于2.x版本,3...

android okhttp的单例和再封装的实例

/**
 * created by zm on 16-2-1
 * okhttp的再封装,对于2.x版本,3.x版本将原有对okhttpclient配置
 * 改成了builder模式配
 * 置,对于超时、代理、dns,okhttp已经做好了配置,
 * 若不需要特殊配置,可以跳过
 */
public class okhttputil
{
  private static okhttpclient singleton;
  //非常有必要,要不此类还是可以被new,但是无法避免反射,好恶心
  private okhttputil(){

  }
  public static okhttpclient getinstance() {
    if (singleton == null)
    {
      synchronized (okhttputil.class)
      {
        if (singleton == null)
        {
          singleton = new okhttpclient();
        }
      }
    }
    return singleton;
  }
}

之前在看okhttp源码的时候,发现square没有对okhttpclient进行单例,网上也没找到合适的解释,以下是自己的猜测

优点:使用单例模式,避免了多次创建所产生的垃圾

缺点:对于一些特殊需求的代码进行一些灵活的配置,单例模式难以实现

总结:做为优秀的开源框架,square出发点是让用户更好更灵活的使用和扩展,从用户角度来说,对于不需要多次配置的项目,可以手动写一个单例模式,便于内存的高效利用

/**
 * okhttp再次封装
 * created by zm on 16-2-1
 * update by zm on 16-3-19 增加builder,方便以后内容或者字段的扩展
 * 
 */
public class httptools
{
  private context context;
  private final requestparams req;
  private final handler handler;

  public httptools(builder builder)
  {
    // todo auto-generated constructor stub
    context = builder.context;
    req = builder.req;
    handler = builder.handler;
  }

  public static class builder
  {
    private final requestparams req;
    private final context context;
    private final handler handler;

    public builder(requestparams req, context mcontext, handler handler)
    {
      // todo auto-generated constructor stub
      this.req = req;
      this.context = mcontext;
      this.handler = handler;
    }

    public httptools build() {
      return new httptools(this);
    }
  }

  public void requestbuilder() {
    // todo auto-generated method stub
    if(req==null||context==null||handler==null){
      throw new nullpointerexception("nullpointerexception");
    }
    requestget(req, context, handler);
  }

  private static void parse(call call, final handler handler,
      final requestparams req) {
    // 请求加入调度
    call.enqueue(new callback()
    {
      @override
      public void onresponse(call call, response response)
          throws ioexception {
        // todo auto-generated method stub
        string result = response.body().string();
        if (result != null)
        {
          message message = message.obtain();
          message.obj = result;
          message.what = req.getsuccessmsgwhat();
          handler.sendmessage(message);
        }
      }

      @override
      public void onfailure(call call, ioexception e) {
        // todo auto-generated method stub
        handler.sendemptymessage(req.getfailmsgwhat());
      }
    });
  }

  /**
   * 
   * @param req
   * @param context
   * @param handler
   * 
   *      get请求
   */
  public static void requestget(final requestparams req,
      final context context, final handler handler) {
    // 创建一个request
    final request request = new request.builder().url(req.getrequesturl()).build();
    call call = okhttputil.getinstance().newcall(request);
    parse(call, handler, req);
  }

  /**
   * post请求
   */
  public static void requestpost(final requestparams req,
      final context context, final handler handler) {
    formbody.builder builder = new formbody.builder();
    //此处是对requestparams的遍历,requestparams类省略
    for (map.entry<string, object> mentry : req.getparamentry())
    {
      string mentrykey = mentry.getkey();
      object mentryvalue = mentry.getvalue();
      if (textutils.isempty(mentrykey))
      {
        continue;
      }
      builder.add(mentrykey, mentryvalue.tostring());
    }
    requestbody body = builder.build();
    request request = new request.builder().url(req.geturl()).post(body).build();

    call call = okhttputil.getinstance().newcall(request);
    parse(call, handler, req);
  }

  /**
   *      数据请求的集中管理,方便以后一键替换,从get到post
   */
  public static void request(requestparams req, context mcontext,
      handler handler) {
    // todo auto-generated method stub
    requestget(req, mcontext, handler);
  }
}

最后再奉献上一个封装类

/**
 * 
 * created by zm on 16-2-1
 * 基于gson的json转model封装类
 *
 */
public class jsontomodel
{

private static string info = "info";

  public static string getinfo()
  {
    return info;
  }

  public static void setinfo(string info)
  {
    jsontomodel.info = info;
  }
  /**
   * 
   * @param msg
   * @param t
   *      model类
   * @param model
   *      model对象
   * @return
   */
  public static <t> list<t> getjsonarraytomodel(message msg, class<t> t,
      t model) {
    // todo auto-generated method stub
    list<t> list = new arraylist<t>();
    try {
      jsonobject json = new jsonobject(msg.obj.tostring());
      for (int i = 0; i < json.getjsonarray(getinfo()).length(); i++) {
        model = gsonhelper.totype(json.getjsonarray(getinfo()).get(i).tostring(), t);
        list.add(model);
      }
      return list;
    } catch (exception e) {
      // todo auto-generated catch block
      log.e("getjsonarraytomodel", "error");
      e.printstacktrace();
    }
    return null;
  }
}

json转model的这个类中,当时没考虑到过多性能的问题,在此类中即使用了org.json.jsonobject也使用了gson,此处还可以做出相应的优化

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!