3

我目前有一个媒体播放器,并试图从我的源路径中获取重定向地址。由于媒体播放器不支持重定向处理,我试图通过创建 httpurlconnection 等来获取重定向的 url 路径。但是,我不确定我是否做得对。任何帮助,将不胜感激。谢谢。

代码:

Log.d(TAG, "create url - test");
URL testUrl = new URL(path);
HttpURLConnection conn = (HttpURLConnection)testUrl.openConnection();

String test = conn.getURL().toString();
String test1 = conn.getHeaderField(2);
String test2 = conn.toString();
Log.d(TAG, "normal stuff test is: " + test);
Log.d(TAG, "header field test is: " + test1);
Log.d(TAG, "url to string is: " + test2);
4

1 回答 1

0

下面的代码遵循一跳 URL 重定向。通过使用HTTP HEAD请求而不是GET,它消耗的带宽大大减少。扩展此方法以处理多跳应该相当简单。

public URI followRedirects(URI original) throws ClientProtocolException, IOException, URISyntaxException
{
    HttpHead headRequest = new HttpHead(original);

    HttpResponse response = client.execute(headRequest);
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY ||
        statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
    {
        String location = response.getHeaders("Location")[0].toString();
        String redirecturl = location.replace("Location: ", "");
        return new URI(redirecturl);
    }
    return original;
}

它假定您已经设置了存储在字段中的HttpClientclient

另请参阅此问题

于 2012-06-07T19:15:11.817 回答