安卓 - 获取URL重定向

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

看看我在这里的回答是否有帮助:https://dev59.com/SGPVa4cB1Zd3GeqP3S0v - yorkw
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;
}

假设您已经设置了存储在字段client中的HttpClient

还请参阅此问题


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接