URL定义: 统一资源定位符(Uniform Resource Locator)是对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。
URL语法格式: protocol://hostname[:port]/path/[?query]
protocol协议:
1、file:资源是本地计算机上的文件。
2、ftp: 通过ftp访问资源
3、gopher: 通过gopher协议访问资源
4、http: 通过http协议访问资源
5、https: 通过安全的协议访问资源
6、mailto: 资源师电子邮件地址
7、MMS: 流媒体相关
8、ed2k,Flashget,thunder: 专用下载链接
[?query] : 传递参数,可有多个参数,用“&”隔开,每个参数的名和值用"="符号隔开。
URL类分析:
构造方法: URL URL(String spec): create a URL object from the String representation
.
重要方法:
1、getHost(): 获得主机
2、getPort(): 获得端口
3、getFile(): 获得URL的路径部分
4、getProtocol(): 获得URL的协议名称
5、InputStream openStream(): 打开到此URL的连接并返回一个用于从该连接读入的InputStream。
6、URLConnection openConnection(): 返回一个URL对象,它表示到URL所引用的远程对象的连接。(这个方法很重要)
代码示意(涉及方法1--5):
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
public class TestURL01 {
public static void main(String[] args) throws MalformedURLException {
String str = "https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/news/q=100/sign=643ba8b7d20735fa97f04ab9ae500f9f/8ad4b31c8701a18b48f518e3982f07082838fe04.jpg";
URL url = new URL(str);
System.out.println(url.getHost());
System.out.println(url.getPort());
System.out.println(url.getFile());
File f = new File("1.jpg");
try {
InputStream is = url.openStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(f));
byte[] b = new byte[1024];
int len = 0;
while ((len = is.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
bos.close();
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
利用URLConnection获得流并下载(下节介绍URLconnection):
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLConnection;
public class TestURLConnection01 {
public static void main(String[] args) {
String str = "https://ss0.baidu.com/7Po3dSag_xI4khGko9WTAnF6hhy/news/q=100/sign=643ba8b7d20735fa97f04ab9ae500f9f/8ad4b31c8701a18b48f518e3982f07082838fe04.jpg";
try {
//确定资源位置
URL url = new URL(str);
//打开连接
URLConnection conn = url.openConnection();
//一些方法
System.out.println(conn.getContentType());
System.out.println(conn.getContentLength());
File file = new File("baby.jpg");
//得到从服务器传入的输入流
BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
//向本地文件写入
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
byte[] b = new byte[1024*12];
int len = 0;
while((len = bis.read(b)) != -1){
bos.write(b, 0, len);
bos.flush();
}
bis.close();
bos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}