这是HttpURLConnection代码,检查互联网连接。我只是想知道他们会自动重复直到连接成功吗?或者我是否需要明确指定任何重试策略
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(500); //choose your own timeframe
urlc.setReadTimeout(500); //choose your own timeframe
urlc.connect();
int responseCode = urlc.getResponseCode();
if (responseCode == 200) {
//if internet is up then execute the jobs
doSomeWork();
} else {
Log.d("Warning", "Internet is not available");
}
答案 0 :(得分:1)
HttpURLConnection没有任何重试策略。你需要自己处理它。
您可以在HttpURLConnection类中使用 getErrorStream()方法来检查包括连接问题在内的错误。如果未建立与服务器的连接,则返回null。
详情可在此处找到 - https://developer.android.com/reference/java/net/HttpURLConnection.html#getErrorStream()