Android HttpURLConnection:处理HTTP重定向 [英] Android HttpURLConnection: Handle HTTP redirects

查看:266
本文介绍了Android HttpURLConnection:处理HTTP重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 HttpURLConnection 来检索这样的网址:

I'm using HttpURLConnection to retrieve an URL just like that:

URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(true);
// ...

我现在想知道是否有重定向如果它是永久的(301)或临时的(302),以便在第一种情况下更新数据库中的URL但不在第二种情况下更新。

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.

是这仍然可以使用 HttpURLConnection 的重定向处理,如果,如何?

Is this possible while still using the redirect handling of HttpURLConnection and if, how?

推荐答案

在调用 getInputStream()后,只需在 URLConnection 实例上调用 getUrl()

Simply call getUrl() on URLConnection instance after calling 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);

这篇关于Android HttpURLConnection:处理HTTP重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆