【问题标题】:MediaPlayer with custom socketFactory带有自定义 socketFactory 的 MediaPlayer
【发布时间】:2017-03-28 09:24:13
【问题描述】:

我有一个带有 自签名证书 的 HTTPS MEDIA 服务器,我想从该服务器在我的 Android 应用程序中流式传输音频。根据developer.android.com 的此链接,为了允许自签名证书,我通过读取 .crt 文件生成了一个证书,使用此证书创建了一个密钥库并将此密钥库初始化为一个 TrustManagerFactory。

CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream caInput = new BufferedInputStream(getResources().openRawResource(R.raw.certificate));
Certificate ca;
try {
    ca = cf.generateCertificate(caInput);
    Log.d(TAG, "ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
    caInput.close();
}

// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);

// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);

// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);

该链接描述了一个将此自定义 SSLContext 与 HttpsURLConnection 对象一起使用的示例。

// Tell the URLConnection to use a SocketFactory from our SSLContext
URL url = new URL("https://certs.cac.washington.edu/CAtest/");
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(context.getSocketFactory());
InputStream in = urlConnection.getInputStream();

但在我的 HTTP 应用程序中,我通过如下设置音频链接来使用 MediaPlayer 类。

MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(address); //address is a String variable like http://example.com/audio.aac

问题是,我如何将上述 SSLContext 的 socketFactory 对象与 MediaPlayer 一起使用,以便 MediaPlayer 可以使用 HTTPS 音频源。

【问题讨论】:

    标签: android https media-player


    【解决方案1】:

    要使用此自定义SSLContext 连接,我们必须在将源提供给媒体播放器之前将socketFactory 对象设置为HttpsURLConnection

    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    

    这允许MediaPlayer 使用我们的自签名证书的连接。

    除此之外,我还必须提供自定义的HostnameVerifier 实现来手动验证subjectAlternateNames。

    final HostnameVerifier hv =
      HttpsURLConnection.getDefaultHostnameVerifier();
    
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
      @Override
      public boolean verify(String hostname, SSLSession session) {
        return hv.verify("www.youdomainname.com", session);
      }
    };
    

    这个自定义的HostnameVerifier 可以通过下面的代码链接到MediaPlayer

    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2012-04-24
      • 1970-01-01
      相关资源
      最近更新 更多