import java.io.IOException;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
//操作从URL中获取网络资源的类
public class Url {
public static void getImageResourcByURL(String imagesFile)
throws IOException {// 获取URL指定的资源
URL url = new URL(imagesFile);
Object obj = url.getContent();// 获得此URL的内容
System.out.println(obj.getClass().getName());// 显示名称
}
public static void getHtmlResourceByURL(String htmlFile) throws IOException {// 获取URL指定的资源
URL url = new URL(htmlFile);
URLConnection uc = url.openConnection();// 创建远程对象连接对象
InputStream in = uc.getInputStream();// 打开的连接读取的输入流
int c;
while ((c = in.read()) != -1) {// 循环读取资源信息
System.out.print((char) c);
}
System.out.println();
in.close();
}
public static void getHTMLResource(String htmlFile) throws IOException {// 读取URL指定的网页内容
URL url = new URL(htmlFile);// 创建URL对象
Reader reader = new InputStreamReader(new BufferedInputStream(
url.openStream()));// 打开URL连接创建一个读对象
int c;
while ((c = reader.read()) != -1) {// 循环读取资源信息
System.out.print((char) c);
}
System.out.println();
reader.close();
}
public static void getResourceOfHTML(String htmlFile) throws IOException {// 读取URL指定的网页内容
URL url = new URL(htmlFile);
InputStream in = url.openStream();// 打开URL连接创建输入流
int c;
while ((c = in.read()) != -1) {// 循环读取资源信息
System.out.print((char) c);
}
System.out.println();
in.close();
}
public static void supportURLType(String host, String file) {// Java所支持的URL类型
String[] schemes = { "http", "https", "ftp", "mailto", "telnet",
"file", "ldap", "gopher", "jdbc", "rmi", "jndi", "jar", "doc",
"netdoc", "nfs", "verbatim", "finger", "daytime",
"systemresource" };// 创建URL类型数组
for (int i = 0; i < schemes.length; i++) {// 循环遍历数组判断是否是java支持的URL类型
try {
URL u = new URL(schemes[i], host, file);
System.out.println(schemes[i] + "是java所支持的URL类型\r\n");
} catch (Exception ex) {
System.out.println(schemes[i] + "不是java所支持的URL类型\r\n");
}
}
}
public static void main(String[] args) throws IOException {
// java程序主入口处
String imageFile = "http://www.baidu.com/001.jpg";
String htmlFile = "http://www.baidu.com/";
String host = "http://www.baidu.com";
String file = "";
System.out.println("1.//获取URL指定的图像资源信息");
getImageResourcByURL(imageFile);
System.out.println("2.获取URL指定的HTML网页资源信息");
getHtmlResourceByURL(htmlFile);
System.out.println("3.根据URL创建读对象读取网页内容");
getHTMLResource(htmlFile);
System.out.println("4.根据URL创建输入流读取网页内容");
getResourceOfHTML(htmlFile);
System.out.println("5.判断Java所支持的URL类型 ");
supportURLType(host, file);
}
}