Java Socket之网络相关API

来源:互联网 发布:微型六轴机器人 淘宝 编辑:程序博客网 时间:2024/05/17 18:41

一、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
原创粉丝点击