java中网络相关API的应用

1、java中InetAddress的应用

//获取本机的InetAddress实例
		InetAddress address = InetAddress.getLocalHost();
		System.out.println("计算机名:" + address.getHostName());
		System.out.println("IP地址:" + address.getHostAddress());
		//获取字节数组形式的IP
		byte[] bytes = address.getAddress();
		System.out.println("字节数组形式的IP地址:" + Arrays.toString(bytes));
		//直接输出InetAddress对象
		System.out.println(address);

计算机名:MSI
IP地址:192.168.232.1
字节数组形式的IP地址:[-64, -88, -24, 1]
MSI/192.168.232.1
//根据主机名获取InetAddress实例
		InetAddress address2 = InetAddress.getByName("MSI");
		System.out.println("计算机名:" + address2.getHostName());
		System.out.println("IP地址:" + address2.getHostAddress());

计算机名:MSI
IP地址:192.168.232.1
//根据主机ip地址获取InetAddress实例
		InetAddress address3 = InetAddress.getByName("192.168.232.1");
		System.out.println("计算机名:" + address3.getHostName());
		System.out.println("IP地址:" + address3.getHostAddress());

计算机名:MSI
IP地址:192.168.232.1

2.java中URL的应用

//创建一个URL实例
			URL ip = new URL("http://www.cctv.com");
			//?后面表示参数,#后面表示锚点
			URL url = new URL(ip, "/index.html?uesrname=tom#test");
			
			System.out.println("协议:" + url.getProtocol());
			System.out.println("主机:" + url.getHost());
			//如果未指定端口号,则使用默认的端口号,此时getPort()方法返回值为-1
			System.out.println("端口:" + url.getPort());
			System.out.println("文件路径:" + url.getPath());
			System.out.println("文件名:" + url.getFile());
			System.out.println("相对路径:" + url.getRef());
			System.out.println("查询字符串:" + url.getQuery());

协议:http
主机:www.cctv.com
端口:-1
文件路径:/index.html
文件名:/index.html?uesrname=tom
相对路径:test
查询字符串:uesrname=tom

public class Ip2test03 {
	public static void main(String[] args) {
		/*
		 * 使用URL读取页面内容
		 */
		
		try {
			//创建一个URL实例
			URL url = new URL("http://www.baidu.com");
			//通过URL的openStream()方法获取URL对象所表示的资源的字节输入流
			InputStream is = url.openStream();
			//将字节输入流转换为字符输入流
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			//为字符输入流添加缓冲
			BufferedReader br = new BufferedReader(isr);
			String data = br.readLine();//读取数据
			//循环读取数据
			while(data!=null) {
				System.out.println(data);//输出数据
				data = br.readLine();//读取下一行
			}
			br.close();
			isr.close();
			is.close();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_42545898/article/details/88065920