Get the final URL of a redirected request with unc

2019-05-08 17:58发布

My code (below) tries to get the final URL returned from a server that does a bit of redirecting. It works fine as long as the URLs have an http scheme. My problem arises when I want to return a URL with a different scheme. Ultimately I want, in some situations, to return a market:// url or other app launch schemes since this is for Android and I want to start Intents with them.

So this gets me as far as retrieving the final http url, but when the final url is market:// it throws the exception seen (java.lang.IllegalStateException: Scheme 'market' not registered), and then getURI doesn't provide that one, it'll provide whatever was before that.

    DefaultHttpClient client = new DefaultHttpClient();
    HttpContext httpContext = new BasicHttpContext();
    HttpGet httpGet = new HttpGet(mInitialUrl);

    try {
        client.execute(httpGet, httpContext);
    } catch (IllegalStateException e) {
        e.printStackTrace();
    }

    // Parse out the final uri. 
    HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
    HttpUriRequest req = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST);

    return (req.getURI().isAbsolute()) ? req.getURI().toString() : (currentHost.toURI() + req.getURI());

Now, I could just register market:// as a scheme, but I don't want to hard-code beforehand what the valid schemes are, I just want it to accept them and return them whatever they are.

Any ideas? Maybe I'm not even taking the right approach. (Changing the server behavior isn't an option in this case... I've got to just deal with the redirects.)

My hope is that someone can tell me how to get the HttpClient to ignore the scheme, or at least preserve the final URI it tries to access.

1条回答
【Aperson】
2楼-- · 2019-05-08 18:52

Using HttpURLConnection for the job works for me. The following of redirects stops without exception when the target resource is not a HTTP resource.

HttpURLConnection connection = (HttpURLConnection) new URL(mInitialUrl).openConnection();
connection.setInstanceFollowRedirects(true);
String location = connection.getHeaderField("location");
查看更多
登录 后发表回答