Can I use Basic HTTP Authentication with Android M

2019-02-28 03:48发布

问题:

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?

回答1:

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();
        }
    });
}


回答2:

I don't think the native media player supports this.



回答3:

Have you tried putting the user ID and password in the URL?

http://<user>:<password>@<host>:<port>/<url-path>


回答4:

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/



回答5:

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.

http://developer.android.com/reference/android/media/MediaPlayer.html#setDataSource(android.content.Context%2C%20android.net.Uri%2C%20java.util.Map%3Cjava.lang.String%2C%20java.lang.String%3E)