首页 > 代码库 > url 获取网络资源

url 获取网络资源

public class Url {

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
        
        try {
            URL url= new URL("http://img2.haoju.cn/upfiles/201212/1355452132.jpg!mid");
            getInfo(url);
        } catch (MalformedURLException e) {
            System.out.println("您的网络出现问题了");
            e.printStackTrace();
            
        }
    }
    
    /**
     *获取url详细信息 
     * @param url
     * @throws IOException 
     */
    public static void getInfo(URL url) throws IOException{

        //方法一
        URLConnection open = url.openConnection();
        
        InputStream input = open.getInputStream();
        OutputStream output = new FileOutputStream("E:\\haoju.html");
        byte[] buffer = new byte[2048];
        int lenth = 0;
        while(-1 !=(lenth = input.read(buffer, 0, buffer.length))){
            output.write(buffer, 0, lenth);
        }
        input.close();
        output.close();
        
        //方法二
        InputStream input = url.openStream();
        OutputStream output = new FileOutputStream("E:\\1.jpg");
        byte[] buffer = new byte[2048];
        int length =0;
        while( -1!=(length =input.read(buffer, 0, buffer.length))){
            output.write(buffer, 0, length);
        }
        input.close();
        output.close();
        System.out.println("----over----");
        
        //方法三
        BufferedReader buffer = new BufferedReader(new InputStreamReader(url.openStream()));
        String line  = null;
        
        while(null != (line=buffer.readLine())){
            System.out.println(line);
        }
        buffer.close();
    }
}

参照:http://www.cnblogs.com/mengdd/archive/2013/03/09/2951877.html

1,创建url对象

2,等到输入流

3,保存或者处理