JAVA URL 操作使用工具类

 

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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值