java,android,解析一个url,获得重定向的uri
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5204599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java, android, resolve an url, get redirected uri
提问by sosergio
I have an authentication protected url : www.domain.com/alias
我有一个受身份验证保护的网址:www.domain.com/alias
that when requested will return another url: www.another.com/resource.mp4 (not protected)
请求时将返回另一个网址:www.another.com/resource.mp4(不受保护)
I would like to know if exists a method in Java that will return the real url from a given one. Something like: second = resolve(first)
我想知道 Java 中是否存在一种方法,可以从给定的 URL 返回真实的 url。类似于:第二个 = 解决(第一)
I'm thinking of loading the first and try to read into the response maybe the location attribute, but since I'm not a java guru I would like to know if Java already faces this.
我正在考虑加载第一个并尝试读取可能是位置属性的响应,但由于我不是 Java 大师,我想知道 Java 是否已经面临这个问题。
回答by Hakan Ozbay
This is a problem i used to have concerning URL redirects. Try the following code:
这是我曾经遇到的有关 URL 重定向的问题。试试下面的代码:
URL url = new URL(url);
HttpURLConnection ucon = (HttpURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
URLConnection conn = secondURL.openConnection();
The "magic" here happens in these 2 steps:
这里的“魔法”发生在以下两个步骤中:
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
By default InstanceFollowRedirects are set to true, but you want to set it to false to capture the second URL. To be able to get that second URL from the first URL, you need to get the header field called "Location".
默认情况下 InstanceFollowRedirects 设置为 true,但您希望将其设置为 false 以捕获第二个 URL。为了能够从第一个 URL 获取第二个 URL,您需要获取名为“Location”的标题字段。
回答by HiltonT
I have eliminated this issue on sites where we have a MikroTik router by using a Layer 7 protocol filter as shown below. This doesn't help the devices off the WiFi network (obviously) but at least gives them some reprieve when they are connected to home and/or work WiFi networks.
我已经通过使用第 7 层协议过滤器在我们有 MikroTik 路由器的站点上消除了这个问题,如下所示。这对脱离 WiFi 网络的设备没有帮助(显然),但至少在它们连接到家庭和/或工作 WiFi 网络时让它们得到一些缓解。
Firstly, create the protocol definition:
首先,创建协议定义:
/ip firewall layer7-protocol
add comment="Frigging javascript redirects on chrome browsers" \
name=Javascript_Redirect \
regexp="^.+(spaces.slimspot.com|mostawesomeoffers.com).*$"
Now, to actually filter this traffic out
现在,要真正过滤掉这些流量
/ip firewall filter
add action=drop chain=forward comment=\
"Block and log Javascript_Redirect L7 Protocol" layer7-protocol=\
Javascript_Redirect log=yes log-prefix=JSredirect_
Other firewalls that have Layer 7 filtering capacity could also block these redirects in a similar way.
其他具有第 7 层过滤能力的防火墙也可以以类似的方式阻止这些重定向。