HttpsURLConnection不适用于Android API 19(但适用于API 22至29)

时间:2019-09-03 21:31:29

标签: java android android-studio networking

所以我在这里迷路了。我进行了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,清单中的权限按顺序显示:

<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

在使用设备时,我得到了上面的消息,而在使用仿真器时却没有得到消息。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

正如David指出的那样,问题在于API 19默认禁用TLS 1.2。解决方法如下:https://gist.github.com/Kane-Shih/2a556fd24604ed9e80d69581c4f912a3