我有一个由BroadcastReceiver
组成的应用程序,该应用程序在网络连接更改时调用(基本上我只想在连接到某个SSID时调用某些URL)。
我有一个悬挂OkHttp请求的奇怪问题。有时请求会立即处理,有时需要10或20秒。我已经尝试为使用过的OkHttpClient设置连接,读取和写入的超时无济于事。电话连接到网络后发出请求。我也尝试在一个单独的线程中发出请求,延迟时间为2秒,但这并没有改变任何内容。
编辑:我添加了一个网络拦截器。有趣的是,即使第一次请求在大多数情况下也会显着延迟。但是,如果我开始使用IP地址而不是google.com,第一个请求会立即弹出拦截器。是否存在DNS问题?
OkHttpClient设置
client = new OkHttpClient.Builder()
.writeTimeout(3, TimeUnit.SECONDS)
.readTimeout(3, TimeUnit.SECONDS)
.connectTimeout(3, TimeUnit.SECONDS)
.followRedirects(true)
.addNetworkInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.d(TAG, "Request to URL: " + request.url());
Response response = chain.proceed(request);
return response;
}
})
.build();
广播接收器
public void onReceive(Context context, Intent intent) {
/* ... */
client.newCall(new Request.Builder()
.url(url)
.build()).enqueue(/* logging callback with
Log.d(TAG, response.toString()); on success*/);
}
清单中的接收者
<receiver
android:name=".WifiReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
Logcat结果,请注意时差
11-24 22:19:49.717 17511 17511 I WifiReceiver: -- Wifi connected ---
11-24 22:19:49.796 D WifiReceiver: Request to URL: http://172.217.22.78/
11-24 22:20:00.300 D WifiReceiver: Request to URL: http://www.google.com/
11-24 22:20:11.363 D WifiReceiver: Request to URL: http://www.google.de/?gfe_rd=cr&ei=gFk3WL3CDdHnugSQ262QCA
11-24 22:20:11.750 17511 18242 D WifiReceiver: Response{protocol=http/1.1, code=200, message=OK, url=http://www.google.de/SQ262QCA}
答案 0 :(得分:4)
我刚刚验证了(通过添加自定义dns解析程序)请求因DNS解析速度慢而阻塞。
11-24 22:29:39.317 D/WifiReceiver: Lookup 172.217.22.78
11-24 22:29:39.372 D/WifiReceiver: Request to URL: http://172.217.22.78/
11-24 22:29:39.425 D/WifiReceiver: Lookup www.google.com
11-24 22:29:49.953 D/WifiReceiver: Request to URL: http://www.google.com/
11-24 22:29:50.291 D/WifiReceiver: Lookup www.google.de
11-24 22:30:00.775 D/WifiReceiver: Request to URL: http://www.google.de/?gfe_rd=cr&ei=zVs3WLmoNdPLugTk8IKoCA
11-24 22:30:01.197 D/WifiReceiver: Response{protocol=http/1.1, code=200, message=OK, url=http://www.google.de/?gfe_rd=cr&ei=zVs3WLmoNdPLugTk8IKoCA}