[英]Java read from URL stream working selectively
Summary : Sample Java code that reads over a URLConnection reads only certain URLs, not others. 摘要 :读取URLConnection的示例Java代码仅读取某些URL,而不读取其他URL。
Details : I have this sample Java code that I am using to read over a URLConnection. 详细信息 :我有此示例Java代码,可用于阅读URLConnection。 When the URL is " http://www.example.com ", the code reads the page content without any issues.
当URL为“ http://www.example.com ”时,代码将读取页面内容而不会出现任何问题。 However, if the URL is " http://www.cnn.com ", the page content is not read
但是,如果URL为“ http://www.cnn.com ”,则不会读取页面内容
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 redirects from http to https but your call doesn't follow redirects. CNN从http重定向到https,但是您的呼叫不跟随重定向。 You are getting a 307 with an empty body so the readline results in a null and your loop is skipped.
您得到的307的主体为空,因此readline结果为null,并且跳过了循环。 Try with https for CNN.
尝试使用https观看CNN。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.