我尝试从 urlA 获取数据,但我一直从 urlA 重定向到 urlB。
我收到响应代码 301(永久移动),但如果我使用任何浏览器(例如 Chrome、Firefox 甚至 Internet Explorer),我仍然可以转到 urlA 而不会被重定向。因此 urlA 仍然存在(浏览器不会从任何类型的缓存中加载它),并且如果您使用网络浏览器,也不会自动将用户重定向到 urlB。
如何强制使用 HttpURLConnection 的 Java 程序转到仍然存在的原始 urlA?
private StringBuffer getHTMLCode(String urlA) throws IOException {
URL url = new URL(urlA);
final String userAgent = "Mozilla/5.0";
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(false); // NO REDIRECT, if I set TRUE I will be redirected to urlB
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", userAgent);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url); // shows my original urlA
System.out.println("Response Code : " + responseCode); // <-- 301 moved permanently
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer htmlCode = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode.append(inputLine);
}
System.out.println(htmlCode); // <head><title>Document Moved</title></head><body><h1>Object Moved</h1>This document may be found <a HREF="urlB">here</a></body>
in.close();
return htmlCode;
}
最佳答案
您正在寻找的代码可能是这个,它使用 setInstanceFollowRedirects
private StringBuffer getHTMLCode(String urlA) throws IOException {
URL url = new URL(urlA);
final String userAgent = "Mozilla/5.0";
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setInstanceFollowRedirects(false); // NO REDIRECT, if I set TRUE I will be redirected to urlB
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", userAgent);
con.setInstanceFollowRedirects(false);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url); // shows my original urlA
System.out.println("Response Code : " + responseCode); // <-- 301 moved permanently
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer htmlCode = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode.append(inputLine);
}
System.out.println(htmlCode); // <head><title>Document Moved</title></head><body><h1>Object Moved</h1>This document may be found <a HREF="urlB">here</a></body>
in.close();
return htmlCode;
}
关于Java HttpURLConnection 避免重定向并转到原始页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35089254/