一、利用URL获取信息
package com.xiafan.study06;
import java.net.*;
public class URLdemo {
public static void main(String[] args) throws MalformedURLException{
URL url = null;
url = new URL("http://localhost:8080/helloworld/index.jsp?username=xf&password=123456");
System.out.println(url.getProtocol());
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getPath());
System.out.println(url.getFile());
System.out.println(url.getQuery());
}
}
二、利用URL进行下载
package com.xiafan.study06;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLdownload {
public static void main(String[] args) throws Exception{
URL url = new URL("https://m701.music.126.net/20210712135441/4baab462173140e9f7c9bdad7b43bcf1/jdyyaac/obj/w5rDlsOJwrLDjj7CmsOj/9781341128/e7f3/938e/246f/17464f5d826223ade3bf52ffce3467e9.m4a");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream is = urlConnection.getInputStream();
FileOutputStream fos = new FileOutputStream("123.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();
}
}