url编程

urlb编程用来获取网络上的资源

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author: wsj
 * @date: 2018/10/14
 * @time: 17:55
 */
//url编程
public class UrlCode {
    public static void main(String[] args) throws Exception{
        //创建一个url的对象
        URL url = new URL("https://www.baidu.com/");
        //读取服务端中的数据 openStream()
        InputStream is = url.openStream();
        byte[] b = new byte[50];
        int len;
        while ((len = is.read(b))!=-1){
            String str = new String(b,0,len);
            System.out.println(str);
        }
        is.close();
        //若有数据读入,又有输出,使用 openConnection()
        URLConnection urlConnection = url.openConnection();
        InputStream is1 = urlConnection.getInputStream();
        FileOutputStream fileOutputStream = new FileOutputStream(new File("baidu.html"));
        byte[] b1 = new byte[100];
        int len1 ;
        while ((len1 = is1.read(b1)) != -1){
           fileOutputStream.write(b1,0,len1);
        }
        fileOutputStream.close();
        is1.close();
    }



}

 

posted @ 2018-10-14 19:08  wsjun  阅读(289)  评论(0编辑  收藏  举报