【问题标题】:Android - obtain url redirectAndroid - 获取 url 重定向
【发布时间】:2012-06-07 16:58:37
【问题描述】:

我目前有一个媒体播放器,并试图从我的源路径中获取重定向地址。由于媒体播放器不支持重定向处理,我试图通过创建 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);

【问题讨论】:

  • 看看我的回答here有没有帮助。

标签: android redirect httpurlconnection android-mediaplayer


【解决方案1】:

下面的代码遵循一跳 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;
}

假设您已经设置了一个 HttpClient 存储在字段 client 中。

另见this question

【讨论】:

    猜你喜欢
    • 2021-09-15
    • 2013-09-07
    • 2013-04-27
    • 2011-07-09
    • 1970-01-01
    • 2013-02-24
    • 1970-01-01
    • 1970-01-01
    • 2013-11-02
    相关资源
    最近更新 更多