3 回答
TA贡献1895条经验 获得超3个赞
TA贡献1860条经验 获得超9个赞
URL resourceUrl, base, next;
Map<String, Integer> visited;
HttpURLConnection conn;
String location;
int times;
...
visited = new HashMap<>();
while (true)
{
times = visited.compute(url, (key, count) -> count == null ? 1 : count + 1);
if (times > 3)
throw new IOException("Stuck in redirect loop");
resourceUrl = new URL(url);
conn = (HttpURLConnection) resourceUrl.openConnection();
conn.setConnectTimeout(15000);
conn.setReadTimeout(15000);
conn.setInstanceFollowRedirects(false); // Make the logic below easier to detect redirections
conn.setRequestProperty("User-Agent", "Mozilla/5.0...");
switch (conn.getResponseCode())
{
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
location = conn.getHeaderField("Location");
location = URLDecoder.decode(location, "UTF-8");
base = new URL(url);
next = new URL(base, location); // Deal with relative URLs
url = next.toExternalForm();
continue;
}
break;
}
is = conn.openStream();
...TA贡献2039条经验 获得超8个赞
HttpURLConnection.setFollowRedirects(false)
conn.setInstanceFollowRedirects(true);
添加回答
举报
