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();
}
}
}
该博客图片来源于尚硅谷宋老师教学课件