Okhttp3使用问题处理

一、导入设置

implementation 'com.squareup.okhttp3:okhttp:3.10.0'

二、使用

private  void fillData()
{
    String url =getString(R.string.serverurl);
    OkHttpClient okHttpClient = new OkHttpClient();


    final Request request = new Request.Builder()
            .url(url)
            .get()//默认就是GET请求,可以不写
            .build();
    final Call call = okHttpClient.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

            Log.i("onfail",e.getMessage());

        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
           

Response response = call.execute();

        call.enqueue(new Callback() {

            @Override

            public void onFailure(Call call, IOException e) {

                Toast.makeText(NetworkActivity.this,call.toString()+e.getMessage(),Toast.LENGTH_SHORT).show();

                Log.i("onfail",call.toString()+e.getMessage());

            }

            @Override

            public void onResponse(Call call, Response response) throws IOException {

                Toast.makeText(NetworkActivity.this,request.body().toString(),Toast.LENGTH_SHORT).show();

                Log.i("success",response.body().toString());

            }

        }) } }); }

debug运行出现错误  Can't create handler inside thread that has not called Looper.prepare()

这是因为异步调用网络请求,主线程更新UII的结果(网上很多博客的例子都是官网的简单翻译而已,https://square.github.io/okhttp/

处理思路:

方法1:需先在该线程中手动开启Looper(Looper.prepare()-->Looper.loop()),然后将其绑定到Handler对象上;

final Runnable runnable = new Runnable() {
  @Override
  public void run() {
    //执行耗时操作
    try {

      Log.e("bm", "runnable线程: " + Thread.currentThread().getId()+ " name:" + Thread.currentThread().getName());

      Thread.sleep(2000);
      Log.e("bm", "执行完耗时操作了~");
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
  }
};
new Thread() {
  public void run() {
    Looper.prepare();
    new Handler().post(runnable);//在子线程中直接去new 一个handler
    Looper.loop();    //这种情况下,Runnable对象是运行在子线程中的,可以进行联网操作,但是不能更新UI
  }
}.start();

修改fillData()为:

private  void fillData()
{
    String url =getString(R.string.serverurl);
    OkHttpClient okHttpClient = new OkHttpClient();


    final Request request = new Request.Builder()
            .url(url)
            .get()//默认就是GET请求,可以不写
            .build();
    final Call call = okHttpClient.newCall(request);

    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

            Log.i("onfail",e.getMessage());

        }
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            try(ResponseBody responseBody = response.body()) {
              if (!response.isSuccessful())throw new IOException(("unexpected code"+response));
               final String  mstring = responseBody.string();
               final Runnable runnable = new Runnable() {
                   @Override
                   public void run() {

                       Toast.makeText(NetworkActivity.this, mstring,Toast.LENGTH_SHORT).show();
                   }
               };
               new Thread(){
                   public void  run(){
                       new Handler(Looper.getMainLooper()).post(runnable);
                   }
               }.start();

            }
        }
    });
}

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值