我的测试用例也无法正常工作,每次需要30多秒:
- Android Emulator Nexus 4 (Android Version 4.1.2)
- 没有互联网连接的Windows 7(确保模拟器没有互联网连接)
等级:
implementation 'com.squareup.okhttp3:okhttp:3.12.2'
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
}
compileSdkVersion 27
buildToolsVersion '28.0.3'
爪哇岛:
public static class CheckIpAsyncTask extends util.android.os.AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
Logger.i(TAG, "API::FBD::checkIpInfo, API_IPINFO = " + API_IPINFO);
if (BuildConfig.DEBUG) {
//ThreadUtil.sleep(10 * TimeUtil.SECOND);
}
Request req = new Request.Builder()
.get()
.url(API_IPINFO)
.build();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(2, TimeUnit.SECONDS)
.callTimeout(2, TimeUnit.SECONDS)
.readTimeout(2, TimeUnit.SECONDS)
.writeTimeout(2, TimeUnit.SECONDS)
.build();
Response response = client.newCall(req).execute();
mHttpCode = response.code();
if (mHttpCode == HttpURLConnection.HTTP_OK) {
boolean appConnected = ServerHelper.checkAppConnected();
if (!appConnected) {
JSONObject res = new JSONObject(response.body().string().trim());
mCountry = res.getString("country").toLowerCase();
mIp = res.getString("ip").toLowerCase();
Logger.i(TAG, "API::FBD::checkIpInfo, res = " + res);
PreferenceHelper.get(mContext).setIpInfoApiCountry(mCountry);
PreferenceHelper.get(mContext).setIpInfoApiHost(mIp);
}
}
} catch (java.io.InterruptedIOException interruptedIOException) {
Logger.e(TAG, "API::FBD::checkIpInfo, InterruptedIOException=" + interruptedIOException);
} catch (Throwable ignored) {
Logger.e(TAG, "API::FBD::checkIpInfo, Throwable=" + ignored);
}
return null;
}
原木:
04-04 06:25:06.940 4492-4645/? I/Toolbox: [PLACE] at com.xy.ui.FbdUtil$CheckIpAsyncTask.doInBackground(FbdUtil.java:98)
[FbdUtil]API::FBD::checkIpInfo, API_IPINFO = http://api.z.com:30070/servers/ipinfo
04-04 06:25:34.960 4492-4645/? E/Toolbox: [PLACE] at com.xy.ui.FbdUtil$CheckIpAsyncTask.doInBackground(FbdUtil.java:129)
[FbdUtil]API::FBD::checkIpInfo, InterruptedIOException=java.io.InterruptedIOException: timeout
模拟器Nexus 6(安卓8.0版)上的日志:
04-04 06:52:44.696 2624-3950/? I/Toolbox: [PLACE] at com.xy.ui.FbdUtil$CheckIpAsyncTask.doInBackground(FbdUtil.java:98)
[FbdUtil]API::FBD::checkIpInfo, API_IPINFO = http://api.z.com:30070/servers/ipinfo
04-04 06:53:59.886 2624-3175/? E/Toolbox: [PLACE] at com.xy.ui.ForbiddenUtil$CheckIpAsyncTask.doInBackground(FbdUtil.java:129)
[FbdUtil]API::FBD::checkIpInfo, InterruptedIOException=java.io.InterruptedIOException: timeout
最后,德米特里·泽诺维奇(Dmitry Zenovich)在“问题6”中的解决方案对我有用:
.dns(hostname -> Single.fromCallable(() -> Arrays.asList(InetAddress.getAllByName(hostname)))
.timeout(2, TimeUnit.SECONDS)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.computation())
.onErrorReturnItem(new ArrayList<>())
.blockingGet())