具有自定义socketFactory的MediaPlayer

时间:2017-03-28 09:24:14

标签: android https media-player

我有一个带有自签名证书的HTTPS MEDIA服务器,我希望在我的Android应用中流式传输音频。根据{{​​3}}的此链接,为了允许自签名证书,我通过读取.crt文件生成了证书,使用此证书创建了一个密钥库,并将此keyStore初始化为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音频源。

1 个答案:

答案 0 :(得分:0)

要使用此自定义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);