【发布时间】:2019-09-03 21:31:29
【问题描述】:
所以我在这里迷路了。我进行 HttpsURLConnection 调用,它在 API 22(模拟器和实际设备)、API 23(设备)和 API 29(模拟器)上运行良好。但它不适用于 API 19(在实际设备和模拟器上都试过)。
public class HttpsCall extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urlString){
HttpsURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL(urlString[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(8000);
urlConnection.setConnectTimeout(8000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder buffer = new StringBuilder();
if (inputStream == null) return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
if (buffer.length() == 0) return null;
return buffer.toString();
} catch (Exception e) {
return null;
} finally{
if (urlConnection != null) urlConnection.disconnect();
if (reader != null) {
try { reader.close(); }
catch (final IOException e) { e.printStackTrace(); }
}
}
}
}
minSdkVersion 是 19,并且 Manifest 中的权限似乎是有序的:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
我没有收到任何错误,只是一个空响应。尝试使用https://api.github.com/users/mralexgray/repos 时,我在控制台中得到以下信息:
09-03 17:12:44.533 I/QCNEA : |NIMS|: getaddrinfo: hostname api.github.com servname NULL numeric 4 appname /system/bin/app_process
09-03 17:12:44.533 I/QCNEA : |NIMS|: getaddrinfo: hostname api.github.com servname NULL numeric 0 appname /system/bin/app_process
使用设备时收到上述消息,使用模拟器时没有。
任何帮助将不胜感激。
【问题讨论】:
-
您正在捕获异常,抑制它,然后返回 null。这不会帮助您调试问题。您应该记录异常(不在 finally 块中)。
-
请注意,Github 的 API 仅使用 TLS 1.2 及更高版本。运行 API 级别 19 的设备可能未启用 TLS。如果没有任何其他信息,这将是我首先要检查的事情之一。
-
@DavidV 确实如此。解决了这个问题,我得到了“javax.net.ssl.SSLException: Connection closed by peer”。确实是因为 TLS 1.2 被禁用了。
-
getInputStream()的结果不能为空,所以测试它没有意义。不要编写无意义的代码。
标签: java android android-studio networking