如何使用Java读取Web页面

Linux大全评论1.4K views阅读模式
  1. import static java.lang.System.out;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.net.URL;  
  10.   
  11.   
  12. public class HtmlHelper {  
  13.       
  14.     private static String urlstring = "http://www.csdn.net";  
  15.     private static String filename = "C:/tmp/csdn.html";  
  16.       
  17.     public static void main(String[] args){  

 

  1. //comment out the following section to add proxy server support  

 

  1.          //System.setProperty("http.proxyHost",conf.proxyhost);   
  2.         //System.setProperty("http.proxyPort",conf.proxyport);   
  3.   
  4.         InputStream is = null;  
  5.         BufferedReader br = null;  
  6.         BufferedWriter bw = null;  
  7.         try {  
  8.             out.println("Downloading html page from " + urlstring);  
  9.             URL url = new URL(urlstring);  
  10.             is = url.openStream(); // throws an IOException   
  11.             br = new BufferedReader(new InputStreamReader(is));  
  12.             bw = new BufferedWriter(new FileWriter(filename));  
  13.             String line = null;  
  14.             while ((line = br.readLine()) != null) {  
  15.                 bw.write(line);  
  16.                 bw.newLine();  
  17.             }  
  18.             bw.flush();  
  19.             out.println("Downloaded to " + filename);  
  20.         } catch (IOException ioe) {  
  21.             ioe.printStackTrace();  
  22.         } finally {  
  23.             try {if (is != null) {is.close();}} catch (IOException ignore) {}  
  24.             try {if (br != null) {br.close();}} catch (IOException ignore) {}  
  25.             try {if (bw != null) {bw.close();}} catch (IOException ignore) {}  
  26.         }  
  27.     }  
  28. }  

企鹅博客
  • 本文由 发表于 2019年8月3日 18:26:25
  • 转载请务必保留本文链接:https://www.qieseo.com/174852.html

发表评论