ExoPlayer2 - How can I make a HTTP 301 redirect work?

后端 未结 1 854
青春惊慌失措
青春惊慌失措 2021-02-13 00:37

I started using ExoPlayer to stream some audio. All was well until I came across an URL that has a \"301 Moved Permanently\" redirect. ExoPlayer2 does not handle that by default

相关标签:
1条回答
  • 2021-02-13 00:52

    The problem described in the issue is about cross-protocol redirects (from http to https or vice versa). Exoplayer supports this, but you have to set allowCrossProtocolRedirects to true. Regular redirects (including 301 redirects) are supported by default. The redirect you're receiving is most likely a cross-protocol redirect.

    To create the data source you're calling:

    DefaultDataSourceFactory(Context context, String userAgent)
    

    This constructor creates a DefaultHttpDataSourceFactory which has allowCrossProtocolRedirects set to false.

    To change this, you need to call:

    DefaultDataSourceFactory(Context context, TransferListener<? super DataSource> listener,
      DataSource.Factory baseDataSourceFactory)
    

    And use your own DefaultHttpDataSourceFactory with allowCrossProtocolRedirects set to true as the baseDataSourceFactory.

    For example:

    String userAgent = Util.getUserAgent(context, applicationInfo.getAppName());
    
    // Default parameters, except allowCrossProtocolRedirects is true
    DefaultHttpDataSourceFactory httpDataSourceFactory = new DefaultHttpDataSourceFactory(
        userAgent,
        null /* listener */,
        DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
        DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
        true /* allowCrossProtocolRedirects */
    );
    
    DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(
        context,
        null /* listener */,
        httpDataSourceFactory
    );
    

    If you need to do this more often you can also create a helper method:

    public static DefaultDataSourceFactory createDataSourceFactory(Context context,
            String userAgent, TransferListener<? super DataSource> listener) {
        // Default parameters, except allowCrossProtocolRedirects is true
        DefaultHttpDataSourceFactory httpDataSourceFactory = new DefaultHttpDataSourceFactory(
            userAgent,
            listener,
            DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
            DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
            true /* allowCrossProtocolRedirects */
        );
    
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(
            context,
            listener,
            httpDataSourceFactory
        );
    
        return dataSourceFactory;
    }
    

    This will allow cross-protocol redirects.

    Sidenote: "301 Moved Permanently" means clients need to update their URL to the new one. "302 Found" is used for regular redirects. If possible, update the URLs that return "301 Moved Permanently".

    0 讨论(0)
提交回复
热议问题