2012-06-07 129 views
2

我目前有一個mediaplayer,並試圖從我的源路徑獲取重定向地址。由於媒體播放器不支持重定向處理,因此我試圖通過創建httpurlconnection等來獲取重定向的url路徑。但是,我不確定我是否正確地進行了操作。任何幫助,將不勝感激。謝謝。Android - 獲取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); 
+0

看看我的答案[這裏](http://stackoverflow.com/questions/10341475/getting-url-after-a-redirect-using-httpclient-executehttpget)有所幫助。 – yorkw

回答

0

下面的代碼如下網址的一跳重定向。通過使用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; 
} 

它假定你已經設置了存儲領域clientHttpClient

另請參閱this question