URL和URLConnection案例

     
package com.neutron.network.url;

import java.net.MalformedURLException;
import java.net.URL;

/**
 * URL案例
 * @author zhanght
 *
 */
public class URLDemo {
	
	/**
	 * 主要查看URL的作用
	 */
	public static void checkURL() throws MalformedURLException{
		URL url = new URL("https://www.baidu.com/index.php?tn=site5566");
		String protocol = url.getProtocol();	// 协议
		String host = url.getHost();			// 主机名
		int port = url.getPort();				// 端口名
		String file = url.getFile();			// 文件名称
		String path = url.getPath();			// 资源路径
		String query = url.getQuery();			// 查询参数
		
		StringBuffer buffer = new StringBuffer("");
		buffer.append("protocol:" + protocol + "\n")
		      .append("host:" + host + "\n")
		      .append("port:" + port + "\n")
		      .append("file:" + file + "\n")
		      .append("path: " + path + "\n")
		      .append("query: "+ query);
		System.out.println(buffer.toString());
	}
	
	public static void main(String[] args) throws MalformedURLException {
		checkURL();
	}

}

package com.neutron.network.url;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

/**
 * URLConnection案例
 * @author zhanght
 *
 */
public class URLConnectionDemo {

	public static void main(String[] args) throws IOException {
		URL url = new URL("https://www.baidu.com/index.php?tn=site5566");
		// 获取url所引用的远程对象的连接,相当于获取socket操作
		URLConnection conn = url.openConnection();
		System.out.println("conn: " + conn);
		// 相当于获取socket中输入流操作
		InputStream in = conn.getInputStream();
		// 存储返回的数据
		byte[] buff = new byte[1024];
		// 读取返回的数据
		int len = in.read(buff);
		System.out.println(new String(buff, 0, len));
		
		/*
		 * URLConnection是应用层api,已经将从传输层传递过来的数据做进一步拆包操作,因此我们没有看到传递过来的数据有数据返回头信息
		 */
	}

//	conn: sun.net.www.protocol.https.DelegateHttpsURLConnection:https://www.baidu.com/index.php?tn=site5566
//	<html>
//	<head>
//		<script>
//			location.replace(location.href.replace("https://","http://"));
//		</script>
//	</head>
//	<body>
//		<noscript><meta http-equiv="refresh" content="0;url=http://www.baidu.com/"></noscript>
//	</body>
//	</html>
}

      注意:URL和URLConnection是应用层API,已经将传输层数据做拆包处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值