gpt4 book ai didi

android - 如何等待 Okhttp 调用的结果以在测试中使用它?

转载 作者:行者123 更新时间:2023-12-02 10:49:38 25 4
gpt4 key购买 nike

我创建了一个方法来检查我的应用程序是否能够使用 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() 上的 Activity 进行测试的地方:

if (NetworkTest.pingTestWeb()) {

// Do something if true...

} else {

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

问题是,我的 pingTestWeb 的默认超时时间为 10000 毫秒,如何让 Activity 仅在 pingTestWeb 为 false 时才创建 AlertDialog?因为它没有等待响应。

最佳答案

您还可以使用 CountDownLatch,这样您就可以在测试中放入异步:

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

CountDownLatch countDownLatch = new CountDownLatch(1);
client.newCall(request).enqueue(new Callback() {

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

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

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

countDownLatch.await();
return resultWeb;
}

关于android - 如何等待 Okhttp 调用的结果以在测试中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34597220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com