网络请求在主线程里面直接封装

这是网络请求的精华,代码量很小
public class Utills {


      private volatile   static Utills   utills;
     private    OkHttpClient client;
      private    Handler handler;
      //单例保证该方法执行后只能在同一时间使用同一个对象
      public static synchronized   Utills getInstance(){
            if (utills == null) {
                  utills=new Utills();
            }
            return utills;
      }

      //构造方法
      public Utills() {
            this.handler = new Handler();
            client =new OkHttpClient();
      }

      //创建接口是为了实现异步调用
      interface CallBacks{
            void getString(String ss);
      }

      //请求网络的方法   注意凡是在callback中的方法都是在子线程中执行
      public void getNetData(String url, final CallBacks callBacks){
            Request request=new Request.Builder().url(url).build();
            client.newCall(request).enqueue(new Callback() {
                  @Override//请求网络失败,失败的原因可以通过IOException e该参数转成String打印出来
                  public void onFailure(Call call, IOException e) {
                        System.out.println("====="+e.toString());
                  }

                  @Override//请求网络成功,请求回来的数据在response中保存,请求的内容在Call任务中保存,同样可以打印出来
                  public void onResponse(final Call call, Response response) throws IOException {
                       final String result= response.body().string();
                        //为什么要使用handler.post是为了把内容发送到主线程中
                        handler.post(new Runnable() {
                              @Override
                              public void run() {
                                    //run里面的方法都在主线中
                                    callBacks.getString(result);
                              }
                        });

                  }
            });
      }
}


2.网路请求的数据简单封装
public class OkhttpUtils {

private static OkHttpClient client new OkHttpClient();
private static OkhttpUtils utils new OkhttpUtils();

public OkhttpUtils() {

}

private static OkhttpUtils okHttpUtils() {
return utils;
}

public void dogetAsync(String url, Callback callback) {
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);

}

public String dogetTB(String url) {
Request request = new Request.Builder().url(url).build();
try {
Response execute = client.newCall(request).execute();
String string = execute.body().string();
return string;

catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值