主机名在 Lollipop 设备中不匹配,但在 Postman 和 marshmallow 设备中工作正常

Hostname does not match in Lollipop devices but works fine in Postman and marshmallow devices

最近 SSL 证书被添加到服务器,所以我将 android 中的 url 从 http://appname.com to https://www.appname.com 更改了,这在 marshmallow 设备和 Postman 上工作正常,但在 Lollipop 设备上抛出 javax.net.ssl.SSLException:证书中的主机名不匹配:www.appname.com != www.companyname.com OR www.companyname.com OR companyname.com

我试过在 setHostnameVerifier 中添加 companyname.com 但它没有帮助。这是代码:

 HashMap<String, String> postDataParams=new HashMap<>();
        postDataParams.put("u_phone",CN);
        postDataParams.put("u_code",st);
        postDataParams.put("device_flag",mob_device);
        postDataParams.put("app_type","PRO");
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                HostnameVerifier hv =
                        HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("companyname.com", session);
            }
        };


        try{

            URL url = new URL("https://www.appname.com/sync/validatecheck.php");
            HttpsURLConnection urlConnection =
                    (HttpsURLConnection)url.openConnection();
            //urlConnection.setHostnameVerifier(hostnameVerifier);
            urlConnection.setReadTimeout(10000);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);

            OutputStream os = urlConnection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=urlConnection.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                while ((line=br.readLine()) != null) {
                    result+=line;
                }
            }
            else {
                result="";

            }
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection "+e.toString());
        }

这可能是什么问题?以及如何解决这个问题?

该错误表示颁发证书的主机名(主题中的 CN 字段)与服务器名称不匹配。

如果您使用的是 URL https://www.appname.com,则证书应颁发给 www.appname.com*.appname.com。证书的主机名是 appname.com 那么错误是正确的,你可以使用 https://appname.com 但不能使用 https://www.appname.com.

https://appname.com 中部署您的服务器,为 www.appname.com 颁发新证书或设置 HostnameVerifier 以允许 www.appname.com