举例说明下载网易云音乐中的某首歌曲。同理替换url可下载图片、文本等内容,FileOutputStream中存储保存文件的名称。
package url;
import javax.net.ssl.HttpsURLConnection;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class UrlDemo {
public static void main(String[] args) throws IOException {
//1.下载url
URL url = new URL("https://m10.music.126.net/20200601140729/1fa060c86d19093102dd6e0409ba1d0f/ymusic/0753/5452/0e5f/09a3d842bcc86c2dd14995b55f87c453.mp3");
//2.连接到该资源
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("路过人间.mp3");
byte[] buffer = new byte[1024];
int len;
while((len = is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
urlConnection.disconnect();
}
}