- URL:统一资源定位符,对应这互联网的某一资源地址
- 格式:
- http://localhost:8800/examples/beauty.jpg?username=Tom
协议 + 主机名 + 端口号 + 资源地址 + 参数列表
- 方法:
- public String getProtocol() 获取该URL的协议名
- public String getHost() 获取该URL的主机名
- public String getPort() 获取该URL的端口号
- public Stirng getPath() 获取该URL的文件路径
- public Stirng getFile() 获取该URL的文件名
- public Stirng getQuery() 获取该URL的查询名
public static void main(String[] args) {
try {
URL url=new URL("http://localhost:8800/examples/beauty.jpg?username=Tom");
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());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
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:8800/examples/beauty.jpg");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
is = urlConnection.getInputStream();
fos = new FileOutputStream("day11\\beauty3.jpg");
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) {
urlConnection.disconnect();
}
}
}
}