一、代码
URLTest类
package com.day0321_1;
import java.net.MalformedURLException;
import java.net.URL;
public class URLTest {
public static void main(String[] args) {
try {
URL url1=new URL("http://localhost:8080/examples/beauty.jpg?username=Tom&password=123");
System.out.println(url1.getProtocol());
System.out.println(url1.getHost());
System.out.println(url1.getPort());
System.out.println(url1.getPath());
System.out.println(url1.getFile());
System.out.println(url1.getQuery());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
URLTest1 类
package com.day0321_1;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLTest1 {
public static void main(String[] args) {
HttpURLConnection urlConnection= null;
InputStream is = null;
FileOutputStream fos= null;
try {
URL url=new URL("http://localhost:8080/examples/beauty.jpg");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("新图片2.png");
byte[] buffer=new byte[1024];
int len;
while((len= is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
System.out.println("图片下载完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(urlConnection!=null){
try {
urlConnection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
二、图片