了解 JDK 中有关HTTP URL 处理的API

public class HttpPageFetch extends TestCase {
	
	//最简单的获取网页内容的示例
	@Test
	public void testFetch01() {
		try {
			String urlString = "http://empower.edtest.com:8080/";
			URL url = new URL(urlString); // 代表了一个网址
			InputStream is = url.openStream(); // 获得网页的内容
			// 将InputStream转换为Reader,并使用缓冲读取,提高效率,同时可以按行读取内容
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上述例子太过简单,假如你需要通过代理来访问网络,那么,你需要的是URLConnection!即,在获取内容之前,先设置代理!
	 */
	public void testFetch02() {
		try {
			String urlString = "http://www.ibm.com/developerworks/cn/java/j-javaroundtable/index.html";
			URL url = new URL(urlString); // 代表了一个网址
			// 首先创建HTTP代理,指定代理的地址和端口
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
					"79.120.193.53", 80));
			/**
			 * 首先打开一个连接对象 可以通过这个对象,在真正发起请求之前,设置一些其它的信息 比如:代理服务器等
			 */
			URLConnection conn = url.openConnection(proxy);
			InputStream is = conn.getInputStream(); // 获得网页的内容
			// 将InputStream转换为Reader,并使用缓冲读取,提高效率,同时可以按行读取内容
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * HttpURLConnection 是URLConnection 的子类,它提供了更多与HTTP 有关的处理方法,
	 * 比如:如果你希望获得服务器响应的HTTP代码,比如:2XX,3XX等 比如:你希望设置是否自动进行客户端重定向(缺省是自动重定向)
	 * 比如:你希望指定向服务器提交的 HTTP METHOD(GET 或POST 等)
	 */
	public void testFetch03() {
		try {
			String urlString = "http://localhost:8080/cms/backend/main.jsp";
			URL url = new URL(urlString); // 代表了一个网址
			// 设置是否自动进行重定向,缺省这个值为true
			HttpURLConnection.setFollowRedirects(false);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			// 设置HTTP METHOD
			conn.setRequestMethod("GET");
			int code = conn.getResponseCode();
			System.out.println("服务器响应代码为:" + code);
			InputStream is = conn.getInputStream();
			// 将InputStream转换为Reader,并使用缓冲读取,提高效率,同时可以按行读取内容
			BufferedReader br = new BufferedReader(new InputStreamReader(is,
					"UTF-8"));
			String line = null;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

 

本文参考:李腾飞学习笔记HttpClient 入门。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值