URL和URLConnection
类 URL
类 URL 代表一个统一资源定位符,它是指向互联网“资源”的指针。资源可以是简单的文件或目录,也可以是对更为复杂的对象的引用,例如对数据库或搜索引擎的查询。
URI 是统一资源标识符,而 URL 是统一资源定位符。因此,笼统地说,每个 URL 都是 URI,但不一定每个 URI 都是 URL。
构造方法摘要 |
|
|
方法摘要 |
|
getHost() |
|
openConnection() |
类 URLConnection
抽象类URLConnection 是所有类的超类,它代表应用程序和 URL 之间的通信链接。此类的实例可用于读取和写入此 URL 引用的资源。
getInputStream() |
下载网络资源
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; public class TestURL { public static void main(String[] args) { try { String str = "***"; URL url = new URL(str); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); FileOutputStream fos = new FileOutputStream("C:/" + str.substring(str.lastIndexOf("/") + 1)); // 开始下载 int len = 0; byte[] buff = new byte[102400]; while ((len = is.read(buff)) != -1) { fos.write(buff, 0, len); fos.flush(); } fos.close(); is.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }