简体   繁体   English

使用非常规方案获取重定向请求的最终URL

[英]Get the final URL of a redirected request with unconventional scheme

My code (below) tries to get the final URL returned from a server that does a bit of redirecting. 我的代码(下面)尝试从服务器返回的最终URL进行一些重定向。 It works fine as long as the URLs have an http scheme. 只要URL具有http方案,它就可以正常工作。 My problem arises when I want to return a URL with a different scheme. 当我想要返回具有不同方案的URL时,我的问题出现了。 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. 最终,我希望在某些情况下返回market:// url或其他应用程序启动方案,因为这是针对Android的,我想与他们一起启动Intent。

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. 所以这让我得到了最终的http url,但是当最终的url是market://它会抛出看到的异常(java.lang.IllegalStateException:Scheme'market'未注册),然后getURI不提供那一个,它将提供之前的任何东西。

    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. 现在,我可以注册market://作为一个方案,但我不想事先硬编码有效的方案是什么,我只是希望它接受它们并将它们返回给它们。

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. 我希望有人可以告诉我如何让HttpClient忽略该方案,或者至少保留它试图访问的最终URI。

Using HttpURLConnection for the job works for me. 使用HttpURLConnection为我的工作。 The following of redirects stops without exception when the target resource is not a HTTP resource. 当目标资源不是HTTP资源时,以下重定向会毫无例外地停止。

HttpURLConnection connection = (HttpURLConnection) new URL(mInitialUrl).openConnection();
connection.setInstanceFollowRedirects(true);
String location = connection.getHeaderField("location");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM