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();

            }
        }
    });
}

 

 

 

 

 

你可能感兴趣的:(Arduino,学习)