首页 > 技术文章 > URL下载实现

zhou-zr 2020-11-15 16:43 原文

URL

https://www.baidu.com/

URL:统一资源定位符

DNS:域名解析 https://www.baidu.com/ 解析成一个ip

1.协议://ip地址:端口/项目名/资源
package com.zr.lesson04;

import java.net.MalformedURLException;
import java.net.URL;

public class URLDemo01 {
    public static void main(String[] args) throws MalformedURLException {
        URL url = new URL("http://localhost:8080/hello/index.jsp?username=zr&password=88");
        System.out.println(url.getProtocol());//协议
        System.out.println(url.getHost());//主机IP
        System.out.println(url.getPort());//端口
        System.out.println(url.getPath());//文件
        System.out.println(url.getFile());//全路径
        System.out.println(url.getQuery());//参数
    }
}

下载歌曲

package com.zr.lesson04;

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

public class URLDown {
    public static void main(String[] args) throws Exception {
        //下载地址
        URL url = new URL("https://m10.music.126.net/20200825221815/b99fa2c540477bc1e8ffefd88ef6bd04/yyaac/
                 obj/wonDkMOGw6XDiTHCmMOi/3530218359/48c9/4784/5a64/948f94563dbf15284e934c955945ed03.m4a");
        //连接到这个资源
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream("m.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read(buffer))!=-1){
            fos.write(buffer,0, len);//写出数据
        }
        fos.close();
        is.close();
        urlConnection.disconnect();
    }
}

推荐阅读