12-2、网络编程之URL

1、URL 访问网上资源

  • 1、URL对象代表统一资源定位器,是指向互联网“资源”的指针。它是用协议名、主机、端口和资源组成,即满足如下格式:

    protocol://host:port/resourceName

    http://www.crazyit.org/index.php

  • 2、通过URL对象的一些方法可以访问该URL对应的资源:

    String getFile():获取该URL的资源名

    String getHost():获取主机名

    String getPath():获取路径部分

    int getPort():获取端口号

	@Test
	public void testURL() throws IOException {
		
		// URL:协议名:主机host:端口:资源;
		URL url = new URL("https://i.cnblogs.com/EditPosts.aspx?opt=1");
		
		String file = url.getFile();//获取该URL的资源名
		System.out.println(file);// /EditPosts.aspx?opt=1
		
		String host = url.getHost();//获取主机名
		System.out.println(host);// i.cnblogs.com
		
		int port = url.getPort();//获取端口号
		System.out.println(port);// -1
		
		String query = url.getQuery();//获取 查询参数
		System.out.println(query);// opt=1
		
		String protocol = url.getProtocol();//获取 协议名
		System.out.println(protocol);// https
	}
  • 3、URL 两个最重要的方法:openConnection()、openStream()
/**
	 * 测试 URL 对象的两个最常用方法
	 * 1、openConnection():该方法用于返回URLConnection对象,表示到URL所引用的远程连接。
	 * 2、openStream():
	 * @Description: TODO:
	 * @return void   
	 * @throws IOException
	 */
	@Test
	public void testURL2() throws IOException {
		URL url = new URL("http://www.baidu.com");
		URLConnection connection = url.openConnection();//4
		InputStream is = connection.getInputStream();//5
		OutputStream os = new FileOutputStream("D:/data.html");
		byte[] buffer = new byte[1024];
		int flag = 0;
		while (-1 != (flag = is.read(buffer, 0, buffer.length))) {
			os.write(buffer, 0, flag);
		}
		os.close();
		is.close();
		
//		1、代码第4行openConnection()该方法用于返回URLConnection对象,表示到URL所引用的远程连接。
//
//		2、代码第5行getInputStream方法,用于返回从此打开的连接读取的输入流。
//
//		3、后面的代码就是我们已经很熟悉的从输入流中读到数据,再通过输出流写入文件。
//
//		4、执行的结果就是我们通过浏览器访问http://www.baidu.com,百度服务器返回的内容。
//
//		5、这里是文本文件,我们将后缀修改为html,然后用浏览器访问,这样看起来更直观:
	}

2、InetAddress

JAVA提供了InetAddress类来代表IP地址。

/**
	 *  JAVA提供了InetAddress类来代表IP地址。
	 * @Description: TODO:
	 * @return void   
	 * @throws IOException
	 */
	@Test
	public void testInetAddress() throws IOException {
		InetAddress address = InetAddress.getLocalHost();
		System.out.println(address);// DESKTOP-DBUI5MI/192.168.240.171
		
		address = InetAddress.getByName("www.baidu.com");
		System.out.println(address);// www.baidu.com/115.239.210.27

	}

posted @ 2021-05-18 09:31  星命定轨  阅读(129)  评论(0编辑  收藏  举报