Java从URL流读取有选择地工作
摘要:通过URL连接读取的示例Java代码只读取某些URL,而不读取其他URL 详细信息:我有一个示例Java代码,用于通过URLConnection读取。当URL为“”时,代码读取页面内容时不会出现任何问题。但是,如果URL为“”,则不会读取页面内容Java从URL流读取有选择地工作,java,urlconnection,Java,Urlconnection,摘要:通过URL连接读取的示例Java代码只读取某些URL,而不读取其他URL 详细信息:我有一个示例Java代码,用于通过URLConnection读取。当URL为“”时,代码读取页面内容时不会出现任何问题。但是,如果URL为“”,则不会读取页面内容 public class StackOverflow { public static void main(String[] args) throws Exception { BufferedReader inputStre
public class StackOverflow {
public static void main(String[] args) throws Exception {
BufferedReader inputStream = null;
try {
String urlStr = "http://www.cnn.com"; // Does not work
// urlStr = "http://www.example.com"; // **Works if this line is uncommented**
URL url = new URL(urlStr);
inputStream = new BufferedReader(new InputStreamReader(url.openStream()));
String textLine = null;
while((textLine = inputStream.readLine()) != null) {
System.out.println(textLine);
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if(inputStream != null) inputStream.close();
}
}
}
CNN从http重定向到https,但您的呼叫不遵循重定向。您将得到一个307,其主体为空,因此readline将导致null,并跳过您的循环。尝试为CNN使用https。请建议处理重定向的最优雅方式,以便代码可以无缝地处理http和https。重定向后面是默认值。@user207421否,它们看起来不是默认值,至少不是Java 8u181上的http-->https,也不是使用
setInstanceFollowRedirects(true)
。这篇文章已经过时(Java5),但可能仍然有效:为什么要将这两个任务分配给url
?对不起,我的错。谢谢你指出。现在已经修好了。这篇文章建议它是经过设计的。我尝试了一些关于setInstanceFollowRedirects(true)
的其他SO建议,但都不起作用。