如果永久移动,则获取新的Url
我正在为一个项目开发一个代码,其中一部分代码是检查Urls(Web站点)列表是否正常并确认它。
到目前为止,每件事都按计划工作,期望一些页面在此列表中永久移动,错误301。 如果出现错误301,我需要获取新的Url信息并在返回true之前将其传递给方法。
以下示例仅移至https,但其他示例可能会移至另一个Url,因此,如果您调用此网站:
http://en.wikipedia.org/wiki/HTTP_301
它移动到
https://en.wikipedia.org/wiki/HTTP_301
哪个好,我只需要获得新的Url。
这可能吗?怎么样?
到目前为止,这是我的工作代码部分:
boolean isUrlOk(String urlInput) { HttpURLConnection connection = null; try { URL url = new URL(urlInput); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.connect(); urlStatusCode = connection.getResponseCode(); } catch (IOException e) { // other error types to be reported e.printStackTrace(); } if (urlStatusCode == 200) { return true; } else if (urlStatusCode == 301) { // call a method with the correct url name // before returning true return true; } return false; }
你可以获得新的URL
String newUrl = connection.getHeaderField("Location");