【Java学习笔记】读取URL

import java.net.URL; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.BufferedReader; 
import java.io.IOException; 
public class ReadUrl1 { 
    public static void main(String arg[]) { 
        String str; 
        try { 
URL url = new URL("http://www.sohu.com/"); 
            InputStream is = url.openStream(); 
            InputStreamReader isr = new InputStreamReader(is); 
            BufferedReader br = new BufferedReader(isr); 
            while((str = br.readLine()) != null) 
                System.out.println(str); 
            br.close(); 
        } catch(IOException e) { 
            System.out.println(e); 
        } 
    } 
}

另一种方法:

import java.net.URL; 
import java.net.URLConnection; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.BufferedReader; 
import java.io.IOException; 
public class ReadUrl2 { 
    public static void main(String arg[]) { 
        String str; 
        try { 
            URL url = new URL("http://www.sohu.com/"); 
            URLConnection uc = url.openConnection(); 
            InputStream is = uc.getInputStream(); 
            InputStreamReader isr = new InputStreamReader(is); 
            BufferedReader br = new BufferedReader(isr); 
            while((str = br.readLine()) != null) 
                System.out.println(str); 
            br.close(); 
        } catch(IOException e) { 
            System.out.println(e); 
        } 
    } 
}

还可以设置代理:

import java.net.URL; 
import java.net.URLConnection; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.util.Properties; 
public class ReadUrl3 { 
    public static void main(String arg[]) { 
        String str; 
        Properties props = System.getProperties(); 
        props.setProperty("proxySet","true"); 
        props.setProperty("proxyPort","8080"); 
        props.setProperty("proxyHost","proxy"); 
        try { 
            URL url = new URL("http://www.sohu.com/"); 
            URLConnection uc = url.openConnection(); 
            InputStream is = uc.getInputStream(); 
            InputStreamReader isr = new InputStreamReader(is); 
            BufferedReader br = new BufferedReader(isr); 
            while((str = br.readLine()) != null) 
                System.out.println(str); 
            br.close(); 
        } catch(IOException e) { 
            System.out.println(e); 
        } 
    } 
}




本文转自gnuhpc博客园博客,原文链接:http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822293.html,如需转载请自行联系原作者

上一篇:用NiceTool 工具解决微信内链接或二维码可直接用外部浏览器打开


下一篇:herl 工具让微信自动打开浏览器