URL编程

2021-02-21  本文已影响0人  DOB_8199


URL网络编程

1.URL:统一资源定位符,对应着互联网的某一资源地址

2.格式:

http://localhost:8080/examples/beauty.jpg?username=Tom

协议  主机名   端口号      资源地址                   参数列表

构造器

常用方法

1.新建URL对象

        URL url =new URL("http://localhost:8080/examples/beauty.jpg");

2. 新建URL链接对象(此处为子类http)

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

3. 获取链接

        urlConnection.connect();

4. 获取输入流

        InputStream is = urlConnection.getInputStream();

5. 保存本地

        FileOutputStream fos =new FileOutputStream("day10\\beauty3.jpg");

        byte[] buffer =new byte[1024];

        int len;

        while((len = is.read(buffer)) != -1){

                fos.write(buffer,0,len);}

        System.out.println("下载完成");

关闭资源

        if(is !=null){

                is.close();}

        if(fos !=null){

                fos.close();}

        if(urlConnection !=null){

                urlConnection.disconnect();}

上一篇 下一篇

猜你喜欢

热点阅读