一、InetAddress类
1.InetAddress类用于标识网络上的硬件资源,标识互联网协议(IP)地址
2.InetAddress没有构造方法,所以不能通过new的方式来生成实体,可以通过静态方法获取实例。
3.测试实例
public class Teso01 {
public static void main(String[] args) throws UnknownHostException {
//获取本机得InetAddress实例
InetAddress inetAddress = InetAddress.getLocalHost();
System.out.println("计算机名:" + inetAddress.getHostName());
System.out.println("IP地址:" + inetAddress.getHostAddress());
byte[] ipBytes = inetAddress.getAddress();//获取字节数组形式的IP地址
System.out.println("字节数组形式的IP: " +Arrays.toString(ipBytes));
System.out.println(inetAddress);
//根据主机名获取InetAddress实例
InetAddress inetAddress1 = InetAddress.getByName("DESKTOP-1O9R96P");
System.out.println("计算机名:" + inetAddress1.getHostName());
System.out.println("IP地址:" + inetAddress1.getHostAddress());
System.out.println("=========================================240");
InetAddress inetAddress2 = InetAddress.getByName("192.168.88.240");
System.out.println("计算机名:" + inetAddress2.getHostName());
System.out.println("IP地址:" + inetAddress2.getHostAddress());
}
}
输出结果
计算机名:DESKTOP-1O9R96P
IP地址:192.168.88.93
字节数组形式的IP: [-64, -88, 88, 93]
DESKTOP-1O9R96P/192.168.88.93
计算机名:DESKTOP-1O9R96P
IP地址:192.168.88.93
=========================================240
计算机名:192.168.88.240
IP地址:192.168.88.240
二、URL
- URL(Uniform Resource Locator)统一资源定位符,表示Internet上某一资源地址
- URL由两部分组成:协议名称和资源名称,中间用冒号隔开
- 在java.net包中,提供了URL类来表示URL
4.URL常用方法实例
public class Test02 {
public static void main(String[] args) {
try {
//创建RUL实例
URL url = new URL("http://www.csdn.net");
//?后面表示参数, #后面表示锚点
URL newUrl = new URL(url,"/index.html?username=tom#test");
System.out.println("协议: "+newUrl.getProtocol());
System.out.println("主机: "+newUrl.getHost());
//如果未指定端口号,则使用默认端口号,此时getPort()方法返回值为-1
System.out.println("端口: "+newUrl.getPort());
System.out.println("文件路径: " + newUrl.getPath());
System.out.println("文件名: " + newUrl.getFile());
System.out.println("相对路径: " + newUrl.getRef());
System.out.println("查询字符串" + newUrl.getQuery());
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
5.使用URL读取网页内容
- 通过URL对象的openStream()方法可以得到指定资源的输入流。
- 通过输入流可以读取、访问网络上的数据
实例
/**
* 使用URL读取网页内容
* */
public class Test03 {
public static void main(String[] args) {
//创建一个URL实例
try {
URL url = new URL("http://www.baidu.com");
//通过URL的openStream方法获取URL对象所表示的资源的字节输入流
InputStream in = url.openStream();
//将字节输入流转成字符输入流
InputStreamReader isr = new InputStreamReader(in,"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();
in.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}