can someone kindly suggest what I'm doing wrong here?
I'm trying to get the header location for a certain URL using Java here is my code:
有人能告诉我我在这里做错了什么吗?我想用Java获取某个URL的头位置,这是我的代码:
URLConnection conn = url.openConnection();
String location = conn.getHeaderField("Location");
it's strange since I know for sure the URL i'm refering to return a Location header and using methods like getContentType() or getContentLength() works perfectly
这很奇怪,因为我确信我所引用的URL返回一个位置头,并使用getContentType()或getContentLength()等方法完美地工作
your advice is much appreciated as always :)
一如既往地感谢您的建议。
Thanks
谢谢
2 个解决方案
#1
14
Perhaps Location
header is returned as a part of redirect response. If so, URLConnection
handles redirect automatically by issuing the second request to the pointed resource, so you need to disable it:
可能位置标头作为重定向响应的一部分返回。如果是,URLConnection通过向指定的资源发出第二个请求来自动处理重定向,因此需要禁用它:
((HttpURLConnection) conn).setInstanceFollowRedirects(false);
EDIT: If you actually need a URL of the redirect target and don't want to disable redirect handling, you may call getURL()
instead (after connection is established).
编辑:如果您确实需要重定向目标的URL,并且不想禁用重定向处理,您可以调用getURL()(在建立连接之后)。
#2
0
Just a follow up to axtavt's answer... If the url has multiple redirects, you could do something like this in order to obtain the direct link:
接下来是axtavt的答案……如果url有多个重定向,您可以这样做,以获得直接链接:
String location = "http://www.example.com/download.php?getFile=1";
HttpURLConnection connection = null;
for (;;) {
URL url = new URL(location);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
String redirectLocation = connection.getHeaderField("Location");
if (redirectLocation == null) break;
location = redirectLocation;
}
#1
14
Perhaps Location
header is returned as a part of redirect response. If so, URLConnection
handles redirect automatically by issuing the second request to the pointed resource, so you need to disable it:
可能位置标头作为重定向响应的一部分返回。如果是,URLConnection通过向指定的资源发出第二个请求来自动处理重定向,因此需要禁用它:
((HttpURLConnection) conn).setInstanceFollowRedirects(false);
EDIT: If you actually need a URL of the redirect target and don't want to disable redirect handling, you may call getURL()
instead (after connection is established).
编辑:如果您确实需要重定向目标的URL,并且不想禁用重定向处理,您可以调用getURL()(在建立连接之后)。
#2
0
Just a follow up to axtavt's answer... If the url has multiple redirects, you could do something like this in order to obtain the direct link:
接下来是axtavt的答案……如果url有多个重定向,您可以这样做,以获得直接链接:
String location = "http://www.example.com/download.php?getFile=1";
HttpURLConnection connection = null;
for (;;) {
URL url = new URL(location);
connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
String redirectLocation = connection.getHeaderField("Location");
if (redirectLocation == null) break;
location = redirectLocation;
}