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

我的未来我决定 提交于 2019-12-03 11:22:03

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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!