Get the final URL of a redirected request with unconventional scheme

◇◆丶佛笑我妖孽 提交于 2019-12-07 09:28:27

问题


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:


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


来源:https://stackoverflow.com/questions/14886313/get-the-final-url-of-a-redirected-request-with-unconventional-scheme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!