43. URL编程

URL简单测试

    @Test
    public void test(){
        try {
            URL url = new URL("https://xueshu.baidu.com/");

            System.out.println(url.getProtocol());//获取协议名
            System.out.println(url.getHost());//获取URL对应的主机名

            System.out.println(url.getPort());//获取URL对应的端口号
            System.out.println(url.getPath());//获取URL对应的文件路径
            System.out.println(url.getFile());//获取URL对应的文件名
            System.out.println(url.getQuery());//获取URL对应的查询名

        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

    }

URL从服务器上下载图片保存到本地

    @Test
    public void test1()  {

        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            String str = new String("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.law315.cn%2Fupload%2Fimg%2FpIOF0Y5KlIKw3hfPpivZPcqvY5QIvPVC7Ht%2FQj4BW1RGCpuofmp7PAPPcsSN9Hy6fe7TTEPAkcJ5UV1wz01qV8F942XB7v0yHI4NTEll8CmhtYgRn5dpw2O0GA.jpg&refer=http%3A%2F%2Fwww.law315.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1623563204&t=d4ca6e60433ee67203e4651e8198eff6");
            URL url = new URL(str);
            //url进行连接,获取到连接的对象
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();

            //连接的对象获取连接,访问服务器
            httpsURLConnection.connect();

            //获取到输入流
            inputStream = httpsURLConnection.getInputStream();
            //将其保存在本地
            fileOutputStream = new FileOutputStream(new File("car.jpg"));
            //保存到本地的过程
            byte[] bytes = new byte[512];
            int len;
            while((len=inputStream.read(bytes))!=-1)
            {
                fileOutputStream.write(bytes,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(fileOutputStream!=null){fileOutputStream.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(inputStream!=null){inputStream.close();}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

该博客图片来源于尚硅谷宋老师教学课件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值