Android HttpURLConnection使用SSL连接,当usesCleartextTraffic被设置为true时,会抛出SSL握手超时异常。

问题描述 投票:0回答:1

我正在构建一个Android应用,需要使用HttpURLConnection来调用一个本地的Web服务。URL是 http:/xxx.xxx.xxx.xxx:8080webservicemovies1。. 它使用Postman给出了正确的响应。然而,在Android Studio中,我不能让连接工作。我已经添加了互联网权限 <uses-permission android:name="android.permission.INTERNET" />,并已设置 android:usesCleartextTraffic="true" 的manifest文件中。但是当我测试下面的方法时,它抛出了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个回答
0
投票

SSL是HTTPS的,不是HTTP的。为什么会出现这种情况呢?如果你把日志贴出来,会告诉你更多的信息,请把manifest.xml也贴出来。

© www.soinside.com 2019 - 2024. All rights reserved.