java Android HttpURLConnection:处理 HTTP 重定向
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15754633/
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
Android HttpURLConnection: Handle HTTP redirects
提问by Julian
I'm using HttpURLConnection
to retrieve an URL just like that:
我正在使用HttpURLConnection
这样的方式检索 URL:
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
// ...
I now want to find out if there was a redirect and if it was a permanent (301) or temporary (302) one in order to update the URL in the database in the first case but not in the second one.
我现在想知道是否有重定向以及它是永久 (301) 还是临时 (302) 重定向,以便在第一种情况下更新数据库中的 URL 而不是在第二种情况下。
Is this possible while still using the redirect handling of HttpURLConnection
and if, how?
在仍然使用重定向处理的同时,这可能HttpURLConnection
吗,如果,如何?
回答by syb0rg
Simply call getUrl()
on URLConnection
instance after calling getInputStream()
:
只需拨打getUrl()
的URLConnection
实例调用后getInputStream()
:
URLConnection con = new URL(url).openConnection();
System.out.println("Orignal URL: " + con.getURL());
con.connect();
System.out.println("Connected URL: " + con.getURL());
InputStream is = con.getInputStream();
System.out.println("Redirected URL: " + con.getURL());
is.close();
If you need to know whether the redirection happened before actually getting it's contents, here is the sample code:
如果您需要在实际获取内容之前知道重定向是否发生,这里是示例代码:
HttpURLConnection con = (HttpURLConnection) (new URL(url).openConnection());
con.setInstanceFollowRedirects(false);
con.connect();
int responseCode = con.getResponseCode();
System.out.println(responseCode);
String location = con.getHeaderField("Location");
System.out.println(location);
回答by danik
private HttpURLConnection openConnection(String url) throws IOException {
HttpURLConnection connection;
boolean redirected;
do {
connection = (HttpURLConnection) new URL(url).openConnection();
int code = connection.getResponseCode();
redirected = code == HTTP_MOVED_PERM || code == HTTP_MOVED_TEMP || code == HTTP_SEE_OTHER;
if (redirected) {
url = connection.getHeaderField("Location");
connection.disconnect();
}
} while (redirected);
return connection;
}