0

我有一个重定向到任何网站的链接。我需要在所有重定向后找到一个 URL。在我收到任何错误响应之前,我的代码运行良好,例如“HTTP 响应代码 401”。

例如,我们将 URL https://google.com缩短为https://short.url

URLConnection con = new URL("https://short.url").openConnection();
InputStream is = con.getInputStream();
URLAfterRedirect = String.valueOf(con.getURL());
is.close();

因此,如果请求正常,我们会在重定向后获得一个 URL ( https://google.com )。但是如果有一些响应代码,它会给我一个我需要的 URL 异常。

java.io.IOException: Server returned HTTP response code: 401 for URL: https://google.com

成功捕获异常后如何获取此 URL?

4

1 回答 1

0

尝试这个:

URLConnection con = new URL("https://short.url").openConnection();

con.setInstanceFollowRedirects(false);
String new_url = con.getHeaderField("Location");
con = new URL(new_url).openConnection();
InputStream is = con.getInputStream();
URLAfterRedirect = String.valueOf(con.getURL());
is.close();
于 2018-10-31T04:27:14.187 回答