(網絡編程)URL下載網絡資源

URL下載網絡資源

URL,統一資源定位符,定位網絡上的某一資源。
可以利用URL下載網絡上的資源。
例如下載網易雲音樂網站的音樂。
在這裏插入圖片描述
複製上述請求URL

public class Demo01Url {
    public static void main(String[] args) throws Exception {
        //1.下載地址
        URL url = new URL("https://m10.music.126.net/20200613222222/ceecf3b10d84ad1b67ebca33acd1220e/yyaac/obj/wonDkMOGw6XDiTHCmMOi/2180584755/addb/4c39/1202/a7e369ca61357fc66eab2467a823d356.m4a");
        //2.鏈接到這個資源
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream is = connection.getInputStream();
        FileOutputStream fos = new FileOutputStream("music.m4a");
        byte[] buffer = new byte[1024];
        int len;
        while ((len=is.read())!=-1){
            fos.write(buffer,0,len);//寫出這個數據
        }
        fos.close();
        is.close();
        connection.disconnect();
    }
}

在這裏插入圖片描述
成功將網絡資源下載到了本地。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章