如何等待Okhttp调用的结果在测试中使用它? [英] How to wait for the result on a Okhttp call to use it on a test?

查看:407
本文介绍了如何等待Okhttp调用的结果在测试中使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一种方法来检查我的应用程序是否能够使用OkHttp连接到服务器.

I've created a method to check if my app is able to connect to my server using OkHttp.

这是我的考试班:

public class NetworkTest {

static boolean resultWeb = false;

public static boolean pingTestWeb() {

    OkHttpClient client = new OkHttpClient();

    Request request = new Request.Builder()
            .url("http://www.google.com")//My server address will go here
            .build();

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

        @Override
        public void onFailure(Request request, IOException e) {
            resultWeb = false;
            Log.i("Error","Failed to connect: "+e.getMessage());
        }

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

            Log.i("Success","Success: "+response.code());
            if (response.code() == 200) {
                resulWeb = true;
            }
        }
    });

    return resultWeb;
}

这是我在OnCreate()上的活动进行测试的地方:

And here is where I'm making the test on my activity on OnCreate():

if (NetworkTest.pingTestWeb()) {

        // Do something if true...

    } else {

        // Do something if false, like showing an AlertDialog...
    }

问题是,我的pingTestWeb的默认超时时间为10000ms,仅当pingTestWeb为false时,如何使活动创建AlertDialog?因为它不等待响应.

The question is, my pingTestWeb have the default Timeout time of 10000ms, how do I make the activity create the AlertDialog only if the pingTestWeb is false? Because it isn't waiting for the response.

推荐答案

我认为这里可能发生的是您正在异步执行OkHttp调用,因此您要在任务完成之前点击return语句.为了测试,可以同步进行OkHttp调用吗?您可以使用下面显示的response.isSuccessful处理成功/失败案例.

I think what may be happening here is you're performing the OkHttp call asynchronously, so you're hitting the return statement before the task is complete. For the sake of the test would it be possible to do the OkHttp call synchronously? You can handle the success/failure case with response.isSuccessful seen below.

   private final OkHttpClient client = new OkHttpClient();

   public void run() throws Exception {
       Request request = new Request.Builder()
           .url("your_url_here")
           .build();

       Response response = client.newCall(request).execute();
       if(response.isSuccessful()){
           return true;             
        }else return false;

    }

这篇关于如何等待Okhttp调用的结果在测试中使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆