package com.itheima.url;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class UrlDemo {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
URL url = new URL("http://e.hiphotos.baidu.com/album/w%3D2048/sign=9b7795ff0b55b3199cf9857577918026/4d086e061d950a7b36bc973a0bd162d9f3d3c947.jpg");
System.out.println("主机名:" + url.getHost());
System.out.println("资源路径" + url .getPath());
System.out.println("端口号:" + url.getPort());
System.out.println("协议名称:" + url.getProtocol());
//通过Url打开连接
URLConnection connection = url.openConnection();
//截取文件名
String filename = url.getPath().substring(url.getPath().lastIndexOf("/"));
//获取连接的输入流对象
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
//通过输入流对象构造输出流对象
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\" + filename));
byte[] bytes = new byte[1024*10];
int len = -1;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
bos.flush();
}
bos.close();
bis.close();
System.out.println("下载完成");
}
}
package com.itheima.url;
import java.net.URLDecoder;
import java.net.URLEncoder;
/**
* url地址编码与解码
* @author Administrator
*
*/
public class URLDemo2 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String url = "http://www.baidu.com/username=小白&password=123";
//把url地址编码为UTF-8格式
url = URLEncoder.encode(url, "UTF-8");
System.out.println(url);
//把url进行解码
url = URLDecoder.decode(url, "UTF-8");
System.out.println(url);
}
}