3

I currently have a mediaplayer and am trying to get the redirect address from my source path. Since the media player does not support redirect handling, I am trying to get the redirected url path by creating a httpurlconnection etc. However, I'm not sure if I am doing it right. Any help would be appreciated. Thanks.

Code:

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);
yorkw
  • 40,926
  • 10
  • 117
  • 130
Splitusa
  • 1,181
  • 7
  • 31
  • 51
  • See if my answer [here](http://stackoverflow.com/questions/10341475/getting-url-after-a-redirect-using-httpclient-executehttpget) helps. – yorkw Jun 08 '12 at 02:28

1 Answers1

0

The code below follows one hop of URL redirects. By using a HTTP HEAD request rather than GET it consumes radically less bandwith. It should be fairly straight forward to extend this method to handle multiple hops.

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

It assumes you have already set up an HttpClient stored in the field client.

Also see this question.

Community
  • 1
  • 1
vidstige
  • 12,492
  • 9
  • 66
  • 110