【问题标题】:Android HttpURLConnection uses SSL connection when usesCleartextTraffic is set to true and throws SSL handshake time out exception当 usesCleartextTraffic 设置为 true 并引发 SSL 握手超时异常时,Android HttpURLConnection 使用 SSL 连接
【发布时间】:2020-09-05 07:09:36
【问题描述】:

我正在构建一个 Android 应用程序,需要使用 HttpURLConnection 来调用本地 Web 服务。 URL 是http://xxx.xxx.xxx.xxx:8080/webservice/movies/1。它使用 Postman 给出正确的响应。
但是,在 Android Studio 中,我无法使连接正常工作。我已经添加了 Internet 权限<uses-permission android:name="android.permission.INTERNET" />,并且已经在清单文件中设置了android:usesCleartextTraffic="true"。但是当我测试以下方法时,它会抛出 SSL 握手超时异常。当 usersCleartextTraffic 设置为 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;
    }

【问题讨论】:

    标签: android httpurlconnection sslhandshakeexception


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-02
      • 2011-04-16
      • 1970-01-01
      • 2018-02-28
      相关资源
      最近更新 更多