Java Socket之网络相关API

一、InetAddress

1. InetAddress类没有构造方法,所以不能直接new出一个对象;
可以通过InetAddress类的静态方法获得InetAddress的对象;
InetAddress.getLocalHost();
InetAddress.getByName();
2. 类主要方法:
String - address.getHostName();
String - address.getHostAddress();
public static InetAddress getByName(String host) throws UnknownHostException
在给定主机名的情况下确定主机的 IP 地址。 
主机名可以是机器名(如 "java.sun.com"),也可以是其 IP 地址的文本表示形式。

二、URL

1. URL(Uniform Resource Locator)统一资源定位符,表示Internet上某一资源的地址。

2. URL由两部分组成:协议名称和资源名称,中间用冒号隔开。

3. 在java.net中提供了URL类来表示URL。

URL读取网页内容:

public static void main(String[] args) {

		try {

			URL url = new URL("http://www.baidu.com");

			System.out.println(url.getHost());
			System.out.println(url.getPort());
			System.out.println(url.getProtocol());

			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();
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值