讀取 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(); } }}
1 回答

波斯汪
TA貢獻1811條經驗 獲得超4個贊
CNN 從 http 重定向到 https,但您的呼叫不遵循重定向。你得到一個空體的 307,所以 readline 導致 null 并且你的循環被跳過。嘗試使用 CNN 的 https。
添加回答
舉報
0/150
提交
取消