摘要:读取URLConnection的示例Java代码仅读取某些URL,而不读取其他URL。
详细信息:我有这个示例Java代码,可用来阅读URLConnection。如果URL为“ http://www.example.com”,则代码将读取页面内容,而不会出现任何问题。但是,如果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();
}
}
}
答案 0 :(得分:0)
CNN从http重定向到https,但是您的呼叫不跟随重定向。您得到的307的主体为空,因此readline结果为null,并且跳过了循环。尝试使用https进行CNN。