Can I use Basic HTTP Authentication with Android MediaPlayer?
-
13-09-2019 - |
Question
I cant find a way to use an url that requires basic auth when im useing mp.setDataSource(url);
MediaPlayer mp = new MediaPlayer();
mp.setDataSource(url);
mp.prepareAsync();
Anyone that got any ideas?
Solution 2
I don't think the native media player supports this.
OTHER TIPS
This worked for me:
public void setupMediaPlayer(){
// Setup Media Player and Prepare to Play
media = new MediaPlayer();
media.setAudioStreamType(AudioManager.STREAM_MUSIC);
// Authdata
String username = "username";
String password = "password";
// encrypt Authdata
byte[] toEncrypt = (username + ":" + password).getBytes();
String encoded = Base64.encodeToString(toEncrypt, Base64.DEFAULT);
// create header
Map<String, String> headers = new HashMap<>();
headers.put("Authorization","Basic "+encoded);
Uri uri = Uri.parse("http://your.full.url:port");
try {
media.setDataSource(this,uri,headers);
} catch (IOException e) {
Log.e(TAG,"Exception "+e.getMessage());
}
media.prepareAsync();
media.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
}
Have you tried putting the user ID and password in the URL?
http://<user>:<password>@<host>:<port>/<url-path>
You could download the mp3 on the cache and play it, here is a post on that http://almondmendoza.com/2010/03/11/play-mediaplayer-with-authentication-on-android/
You can pass HTTP headers, including basic auth headers, in MediaPlayer requests using the following method, which is available in Android API level 14 and above.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow