Android HttpURLConnection 在 use CleartextTraffic 设置为 true 时使



我正在构建一个Android应用程序,需要使用HttpURLConnection来调用本地Web服务。网址 http://xxx.xxx.xxx.xxx:8080/webservice/movies/1。它使用邮递员给出正确的响应。
但是,在安卓工作室中,我无法让连接正常工作。我已经添加了互联网权限<uses-permission android:name="android.permission.INTERNET" />,并且已经在清单文件中设置了android:usesCleartextTraffic="true"。但是当我测试以下方法时,它会抛出 SSL 握手超时异常。为什么当用户明文流量设置为 true 时,它仍然尝试使用 SSL 连接?我应该如何解决此问题?

public static ArrayList<MovieViewModel> GetTop5Movies(int personId) {
ArrayList<MovieViewModel> movieList = new ArrayList<MovieViewModel>();
URL url = null;
HttpURLConnection conn = null;
String textResult = "";
try {
url = new URL(BaseURL.GET_TOP5_MOVIES_URL + personId);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Accept", "application/json");
//It throws expection when it gets to the following line
Scanner inStream = new Scanner(conn.getInputStream());
while (inStream.hasNextLine()) {
textResult += inStream.nextLine();
}
Log.i("Movies", textResult);
JSONArray jsonArray = new JSONArray(textResult);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
movieList.add(new MovieViewModel(jsonObject.getString("Name"), jsonObject.getString("ReleaseDate"), jsonObject.getInt("RatingScore")));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return movieList;
}

SSL 用于 HTTPS 而不是用于 HTTP。为什么要给这个?如果您发布日志,会告诉您更多信息。 也请发布清单.xml。

最新更新