在我的android应用程序中,我试图检查是否有互联网接入,以及是否需要下载一些数据。但是,当我运行下面的代码来验证连接时,它返回的是.getResponseCode()方法-1而不是200,即使有一个有效的连接。该设备通过4G或WIFI连接到互联网上,但不起作用。安装在设备上的其他应用程序可以访问互联网。
protected Boolean doInBackground(String... args) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}AndroidManifests.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sg.help">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />UPDATE添加了以下调试输出。如您所见,responseCode是-1。
urlc = {HttpURLConnectionImpl@19895} "com.android.okhttp.internal.http.HttpURLConnectionImpl:http://www.google.com"
client = {OkHttpClient@19909}
handshake = null
httpEngine = {HttpEngine@19910}
httpEngineFailure = null
requestHeaders = {Headers$Builder@19911}
route = {Route@19912}
fixedContentLength = -1
redirectionCount = 0
method = {String@19913} "GET"
responseMessage = null
fixedContentLengthLong = -1
chunkLength = -1
fixedContentLength = -1
instanceFollowRedirects = true
responseCode = -1
contentType = null
defaultHandler = {URLConnection$DefaultContentHandler@19914}
url = {URL@19883} "http://www.google.com"
allowUserInteraction = false
ifModifiedSince = 0
lastModified = -1
connectTimeout = 0
connected = true
doInput = true
doOutput = false
readTimeout = 0
useCaches = true
shadow$_klass_ = {Class@17437} "class com.android.okhttp.internal.http.HttpURLConnectionImpl"
shadow$_monitor_ = -1761921262发布于 2016-02-15 04:29:24
尝试更改您的URL,例如https://www.android.com/。此外,尝试断开您的httpconnection之后,看看它是否有帮助。
断开连接。一旦读取了响应体,就应该通过调用disconnect()来关闭HttpURLConnection。断开连接会释放连接所持有的资源,因此它们可能会被关闭或重用。
http://developer.android.com/reference/java/net/HttpURLConnection.html
试试看以下几点。
URL url = new URL("https://www.android.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(5000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
urlc.disconnect();
return true;
}https://stackoverflow.com/questions/35400907
复制相似问题