gpt4 book ai didi

java - HttpURLConnection.getResponse 代码错误

转载 作者:可可西里 更新时间:2023-11-01 11:43:05 35 4
gpt4 key购买 nike

在我的 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" />

更新 添加了调试的以下输出。如您所见,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

最佳答案

尝试更改您的网址,例如https://www.android.com/ .此外,之后尝试断开您的 http 连接,看看是否有帮助。

Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

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;
}

关于java - HttpURLConnection.getResponse 代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35400907/

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