歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 如何使用Java讀取Web頁面

如何使用Java讀取Web頁面

日期:2017/3/1 10:23:34   编辑:Linux編程

如何使用Java讀取Web頁面:

  1. import static java.lang.System.out;
  2. import java.io.BufferedReader;
  3. import java.io.BufferedWriter;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.InputStreamReader;
  8. import java.net.URL;
  9. public class HtmlHelper {
  10. private static String urlstring = "http://www.csdn.net";
  11. private static String filename = "C:/tmp/csdn.html";
  12. 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. InputStream is = null;
  4. BufferedReader br = null;
  5. BufferedWriter bw = null;
  6. try {
  7. out.println("Downloading html page from " + urlstring);
  8. URL url = new URL(urlstring);
  9. is = url.openStream(); // throws an IOException
  10. br = new BufferedReader(new InputStreamReader(is));
  11. bw = new BufferedWriter(new FileWriter(filename));
  12. String line = null;
  13. while ((line = br.readLine()) != null) {
  14. bw.write(line);
  15. bw.newLine();
  16. }
  17. bw.flush();
  18. out.println("Downloaded to " + filename);
  19. } catch (IOException ioe) {
  20. ioe.printStackTrace();
  21. } finally {
  22. try {if (is != null) {is.close();}} catch (IOException ignore) {}
  23. try {if (br != null) {br.close();}} catch (IOException ignore) {}
  24. try {if (bw != null) {bw.close();}} catch (IOException ignore) {}
  25. }
  26. }
  27. }
Copyright © Linux教程網 All Rights Reserved