无法使用Java的URLConnection获取响应头位置 [英] can't get response header location using Java's URLConnection
问题描述
有人可以在这里建议我做错了吗?
我正在尝试使用Java获取某个URL的标头位置
这里是我的代码:
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:
URLConnection conn = url.openConnection();
String location = conn.getHeaderField("Location");
这很奇怪,因为我确实知道我正在引用的URL返回Location头并使用方法像getContentType()或getContentLength()完美地工作
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
你的建议一如既往地受到赞赏:)
your advice is much appreciated as always :)
谢谢
推荐答案
或许位置
标头作为重定向响应的一部分返回。如果是这样, URLConnection
通过向指向的资源发出第二个请求来自动处理重定向,因此您需要禁用它:
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:
((HttpURLConnection) conn).setInstanceFollowRedirects(false);
编辑:
如果您确实需要的网址是重定向目标并且不想禁用重定向处理,您可以调用 getURL()
代替(建立连接后)。
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).
这篇关于无法使用Java的URLConnection获取响应头位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!